Case_when 还是 if else?

huangapple go评论83阅读模式
英文:

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":

Case_when 还是 if else?

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 &lt;- case_when(
    df$value &gt;= 0.0 &amp; df$value &lt;= 0.3 ~ 1,
    df$value &gt; 0.4 &amp; df$value &lt;= 0.5 ~ 2,
    df$value &gt; 0.5 ~ 3
)

huangapple
  • 本文由 发表于 2023年6月12日 07:15:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76452865.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定