R中具有特定条件的多列变异

jhy*_*eon 2 if-statement r multiple-columns conditional-statements dplyr

我有这个数据

M1  M2  M3 UCL
1   2   3   1.5
Run Code Online (Sandbox Code Playgroud)

我想在这种情况下创建新列:

如果M1大于UCL,MM1将为“UP”,否则为“NULL”

如果M2大于UCL,MM2将为“UP”,否则为“NULL”

如果M3大于UCL,MM3将为“UP”,否则为“NULL”

M1  M2  M3 UCL   | MM1  MM2 MM3
1   2   3   1.5  | NULL UP  UP
Run Code Online (Sandbox Code Playgroud)

但我有几个M列(如M1~M1005),所以我想编写一些代码,如mutate_each和mutate_at。如何使用 mutate 和 ifelse 函数来在特定条件下创建新列?

mee*_*ram 5

这是一个简单的dplyr解决方案。请注意,向新变量添加后缀(例如 getM1_M而不是 )更容易MM1colnames但是,如果您热衷于重命名它们,则可以稍后设置(请参阅此处以了解如何执行此操作)。

我将结果显示为 a,tibble以便您可以看到列类型。请注意,一旦新列中同时包含 anUP和 an NA,它将从逻辑类型更改为字符类型。

library(dplyr)

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

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

mydf %>% 
    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
Run Code Online (Sandbox Code Playgroud)