英文:
Case_when or if else?
问题
我有一个像这样的数据集,其中有"value"列:
我想用R创建"code"列,意思是:
- 值:在0.0到0.3之间 --> 代码: 1
 - 值:在0.40到0.50之间 --> 代码: 2
 - 值:>50 --> 代码: 3
 
除了case_when(据我了解,它只适用于两个条件),我应该使用什么?
英文:
I have a dataset like this with the column "value":
I want to create with R the column "code", meaning that:
- Values: between 0.0 to 0.3 --> code: 1
 - Values: between 0.40 to 0.50 --> code: 2
 - Values: >50 --> code: 3
 
What should I use instead of case_when (which for my knowledge works only for two conditions)?
答案1
得分: 1
实际上,case_when() 函数处理多个条件,而 ifelse() 只处理一个条件(除非您链接多次调用)。您可以在这里使用 case_when:
df$code <- case_when(
    df$value >= 0.0 & df$value <= 0.3 ~ 1,
    df$value > 0.4 & df$value <= 0.5 ~ 2,
    df$value > 0.5 ~ 3
)
英文:
Actually, the case_when() function handles multiple conditions, whereas ifelse() handles only one (unless you chain calls).  You may use case_when here:
<!-- language: r -->
df$code <- case_when(
    df$value >= 0.0 & df$value <= 0.3 ~ 1,
    df$value > 0.4 & df$value <= 0.5 ~ 2,
    df$value > 0.5 ~ 3
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。



评论