Sinval
Sinval

Reputation: 1417

How to program a condition (if, ifelse) in r that chooses one or more elements of a vector?

How to program a condition in r that chooses one or two elements of a vector? I tried to use ifelse() but it demands to have the same length both in test and yes, no arguments.

 object <- sample(c("A","B","C"),1)

ifelse(object %in% c("A","A"), c(1,2),

       ifelse(object=="B", 1,

              ifelse(object=="C",2,NaN)))

I want to obtain 1,2 when object is "A"

Upvotes: 0

Views: 42

Answers (1)

akrun
akrun

Reputation: 887221

If the object is of length 1, we can use if/else

f1 <- function(obj) if(obj == 'A') 1:2 else if(obj == 'B') 1 else if(obj == 'C') 2 else NaN
f1(object)
#[1] 1 2

Or with switch

f2 <- function(obj) switch(obj, 'A' = 1:2, 'B' = 1, 'C' = 2,  NaN)

f2(object)
#[1] 1 2

f2('B')
#[1] 1
f2('C')
#[1] 2

f2('D')
#[1] NaN

Upvotes: 1

Related Questions