首页 > 解决方案 > 在 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")))))

有比这种方式更好的选择吗?

标签: rif-statementconditional-statements

解决方案


转变?https://www.datamentor.io/r-programming/switch-function/

这将使您的示例:

df$col2<-switch(df$col1, "001" = "Green", "005" = "Blue", "006" = "Pink", "007" = "Other")

推荐阅读