简体   繁体   中英

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

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

With this logic: if a>10, b=double. And if a<10, b=single.

How can I do it?

a b
2 single
2 single
4 single
11 double
12 double
12 double
45 double
4 single

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

You haven't specified what to do in the case a=10, so I have it default to single.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM