r - 嵌套 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))))))
我必须对许多变量和许多类别进行此操作,所以我希望有一种方法可以简化。谢谢!
解决方案
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)
推荐阅读
- java - Spring AOP 没有错误但不执行通知
- c# - 实体框架代码优先:生产环境 - Id 不能为空
- windows - 如何在不杀死其他 cmds 的情况下杀死一个 cmd 进程?
- c# - 当我在数据库中进行更改时,触发器是否会触发 RowChanged 事件?
- vba - 参数不是可选的 - 简单的 VBA 函数
- python - 对于 scipy.stats.f_oneway 中的 F 值,“inf”是什么意思?
- java - Spring JPA 使用单引号内的参数编写本机查询
- r - 如何预测许多产品的时间序列,包括 R 中的季节性因素
- java - Java - 解析未格式化的字符串
- android - Context.startForegroundService 然后没有调用 Service.startForeground