How can I assign a value using if-else conditions in R

后端 未结 2 1468
你的背包
你的背包 2020-11-30 15:39

I have this dataframe with a column a. I would like to add a different column \'b\' based on column \'a\'.

For: if a>=10, b=\'double\'. Otherwise b=\'sing         


        
相关标签:
2条回答
  • 2020-11-30 16:04

    You can use ifelse to act on vectors with if statements.

    ifelse(a>=10, "double", "single")
    

    So your code could look like this

    mydata <- cbind(a, ifelse(a>10, "double", "single"))
    

    (Specified in comments below that if a=10, then "double")

    0 讨论(0)
  • 2020-11-30 16:10

    Strictly speaking, if-else is assignable in r, that is

    x1 <- if (TRUE) 1 else 2
    

    is legit. For details see https://adv-r.hadley.nz/control-flow.html#choices

    However, as this vectorizes over neither the test condition nor the value branches, it's not applicable to the particular case described in the question details, which is about adding a column in a conditional manner. In such a situation ifelse or the more typesafe if_else (from dplyr) can be used.

    0 讨论(0)
提交回复
热议问题