r - 在 R 中有比嵌套 if else 语句更好的选择吗?我想用更少的括号做一些更干净的东西
问题描述
例如我正在使用这个。虽然它有效,但我必须输入更多的条目,我无法想象在我的代码向右移动时最后创建这么多括号。
df$col2<-ifelse(df$col1 == "001","Green",
ifelse(df$col1 == "005", "Blue",
ifelse(df$col1 == "009", "Yellow",
ifelse(df$col1 == "006", "Pink",
ifelse(df$col1 == "007","Other")))))
有比这种方式更好的选择吗?
解决方案
转变?https://www.datamentor.io/r-programming/switch-function/
这将使您的示例:
df$col2<-switch(df$col1, "001" = "Green", "005" = "Blue", "006" = "Pink", "007" = "Other")
推荐阅读
- flutter - 当小部件到达屏幕的某个位置时如何触发事件?
- javascript - 如何通过函数创建按钮传递对象
- spring-boot - 在 Spring Boot 中使用 OAuth 访问令牌作为 JWT 会话的密码是否不安全?
- javascript - 通过 Javascript 隐藏具有特定样式的 Html 元素
- javascript - 如何使元素从屏幕上完全消失而不会出现故障?
- python - 无法使用 PRAW 从 2020 年 12 月 3 日之前发布的子版块中提取帖子
- java - 在 Java 中使用“Dozer”将日期/时间字符串映射到 java.sql.Timestamp 并保存在 DB 中将时间写入 00:00:00.000000
- python - 如何根据标签映射字典转换列表列表中的元素?
- flutter - UI颤动上未选择的RadioListTile列表
- c++ - 试图查找子 cstring 是否存在于 cstring 中