Tomas
Tomas

Reputation: 59515

if function or ? : operator in R

I'm looking for something like cond ? a : b or if(cond, a, b) in R (cond is some condition, returning vector of TRUE/FALSE). I know that in many cases I can use trick with the assignment:

tmp[cond] <- a

but this is not good for me as I don't want to change anything - I just need to get immediate R-value in expression. Thanks!

Upvotes: 0

Views: 313

Answers (1)

Sven Hohenstein
Sven Hohenstein

Reputation: 81693

ifelse(cond, a, b)

will do the trick if a and b are single values or both have the same length as cond. Otherwise, you have

if (cond) a else b

where cond must have length 1 and a and b can have any length.

Upvotes: 4

Related Questions