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

Solution 1:

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

Solution 2:

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.