首页 > 解决方案 > 嵌套 ifelse 函数是否有 R 函数?

问题描述

我正在尝试使用 ifelse 组合许多变量来确定某人是否属于一个职业类别的虚拟变量。我想知道是否有一个功能可以简化此代码并使其更容易重复前进。例如,我的代码目前是:

occupation_blue_collar <- ifelse(occupation=="Blue Collar", T, 
                          ifelse(occupation =="Blue Collar and Ex-Military", T, 
                          ifelse(occupation == "Blue Collar and Non-military Government", T,
                          ifelse(occupation== "Blue Collar and School Student", T,
                          ifelse(occupation== "Blue Collar and University Student", T,
                          ifelse(occupation== "Blue Collar and White Collar", T,       
                                        F))))))

我必须对许多变量和许多类别进行此操作,所以我希望有一种方法可以简化。谢谢!

标签: rif-statementdplyr

解决方案


ifelse您可以通过stringr::str_detect在测试表达式中使用来简化您的语句 -

ifelse(str_detect(occupation, “Blue Collar”, TRUE, FALSE))

如果你有很多变量,那么dplyr::case_when会更好 -

case_when(str_detect(occupation, “Blue Collar”) ~ TRUE,
          str_detect(occupation, “White Collar) ~ TRUE,
          TRUE ~ FALSE)

推荐阅读