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
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")
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.