If a variable belongs to a set

Viewed 79

I would like to write the following if condition

if( (k==1)| (k==4)| (k==8) | (k== 11)| (k==12)){
       ....
} else{
       ....
}

in a more compact way, e.g. like in php where in_array checks if a value exists in an array.

2 Answers

You may use any.

f <- function(k) if (any(k %in% c(1, 4, 8, 11, 12))) 1 else 0
f(1:12)
# [1] 1
f(13:15)
# [1] 0
f(c(1, 4, 8, 11, 12, 13, 14))
# [1] 1
f(c(2, 5, 9, 13, 14))
# [1] 0
f(c(1, 2, 5, 9, 13, 14))
# [1] 1

Further: all() can be used if 'and' logic is desired instead of 'or'.

Related