R函数具有可变数量的ifelse参数

时间:2016-12-25 10:27:01

标签: r

我有一个创建列的脚本,以便我知道哪个规则应该应用于数据框中的每一行。

EndoSubset$FU_Group<-ifelse(EndoSubset$IMorNoIM=="No_IM","Rule1",
                            ifelse(EndoSubset$IMorNoIM=="IM","Rule2",
                             ifelse(EndoSubset$IMorNoIM=="AnotherIM","Rule3",
                           "NoRules")))

我想将它变成一个函数,以便列可以有任意数量的规则和任意数量的条件,因此它可以是:

  EndoSubset$FU_Group<-ifelse(EndoSubset$IMorNoIM=="No_IM","Rule1",
                                ifelse(EndoSubset$IMorNoIM=="IM","Rule2",
                                ifelse(EndoSubset$IMorNoIM=="AnotherIM","Rule3",
                                ifelse(EndoSubset$IMorNoIM=="SomeOtherIM","Rule4",
                                ifelse(EndoSubset$IMorNoIM=="LotsOfIM","Rule5",
                               "NoRules")))

我知道我可以使用省略号,但我不明白如何同时使用这个条件字符串(“No_IM”,IM,“AnotherIM”等)和规则字符串( “Rule1”,“Rule2”,“Rule3”等。)

1 个答案:

答案 0 :(得分:2)

此答案基于另一个已删除的不完整答案。

您可以使用case_when()包中的dplyr来实现此目的。它需要任意数量的条件。由于您没有提供可重现的示例,因此我将展示如何使用mtcars

library(dplyr)
mtcars$cyl_group <- case_when(mtcars$cyl == 4 ~ "Rule1",
                              mtcars$cyl == 6 ~ "Rule2",
                              TRUE ~ "NoRules")
mtcars[2:5, ]
##                    mpg cyl disp  hp drat    wt  qsec vs am gear carb cyl_group
## Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4     Rule2
## Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1     Rule1
## Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1     Rule2
## Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2   NoRules

如您所见,您可以使用~轻松地将条件与值相关联。你的两个例子可能会像这样解决(我不能检查这个,因为你不能提供你的数据):

EndoSubset$FU_Group <- case_when(EndoSubset$IMorNoIM == "No_IM" ~ "Rule1",
                                 EndoSubset$IMorNoIM == "IM" ~ "Rule2",
                                 EndoSubset$IMorNoIM == "AnotherIM" ~ "Rule3",
                                 TRUE ~ "NoRules")

EndoSubset$FU_Group <- case_when(EndoSubset$IMorNoIM == "No_IM" ~ "Rule1",
                                 EndoSubset$IMorNoIM == "IM" ~ "Rule2",
                                 EndoSubset$IMorNoIM == "AnotherIM" ~ "Rule3",
                                 EndoSubset$IMorNoIM == "SomeOtherIM" ~ "Rule4",
                                 EndoSubset$IMorNoIM == "LotsOfIM" ~ "Rule5",
                                 TRUE ~ "NoRules")