Mutate multiple columns with a certain condition in R

二次信任 提交于 2019-12-10 23:15:11

问题


I have this data

M1  M2  M3 UCL
1   2   3   1.5

I would like to make new columns with this condition:

If M1 is more than UCL, MM1 will be "UP" and otherwise "NULL"

If M2 is more than UCL, MM2 will be "UP" and otherwise "NULL"

If M3 is more than UCL, MM3 will be "UP" and otherwise "NULL"

M1  M2  M3 UCL   | MM1  MM2 MM3
1   2   3   1.5  | NULL UP  UP

But I have several M column (like M1~M1005) so that I would like to make some code such as mutate_each and mutate_at. How do I use the function using mutate and ifelse in order to make new columns under a particular condition?


回答1:


Here is a simple dplyr solution. Note that it is easier to add a suffix to the new variables e.g. to get M1_M rather than MM1. However, you can set the colnames afterwards if you were keen to rename them (see e.g. here on how to do that).

I show the result as a tibble so you can see the column types. Note that once a new column has a both an UP and an NA in it, it will change from a logical type to a character type.

library(dplyr)

textdata <- "M1  M2  M3 UCL
1   2   3   1.5"

mydf <- read.table(text = textdata, header = T)

mydf %>% 
    mutate_if(is.integer, as.numeric) %>% 
    mutate_at(vars(starts_with("M")), funs(M = ifelse(. > UCL, "UP", NA))) %>% 
    tibble::as.tibble()

# A tibble: 1 x 7
     M1    M2    M3   UCL  M1_M  M2_M  M3_M
  <dbl> <dbl> <dbl> <dbl> <lgl> <chr> <chr>
1     1     2     3   1.5    NA    UP    UP



回答2:


With base R:

dt=read.table(text="M1  M2  M3 UCL
1   2   3   1.5",header=T)

ncols = ncol(dt)
dt = cbind(dt,ifelse(subset(df, select=M1:M3)>dt[,"UCL"],"UP","NULL"))
colnames(dt)[ncols:ncol(dt)] = paste0("M",colnames(dt)[ncols:ncol(dt)])

result:

   M1 M2 M3 MUCL  MM1 MM2 MM3
1   1  2  3  1.5 NULL  UP  UP


来源:https://stackoverflow.com/questions/45321303/mutate-multiple-columns-with-a-certain-condition-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!