Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 views
in R Programming by (50.2k points)

Let take an instance, I want to have the following if statement in a more compact way, like in php where in_array checks if a value exists in an array:

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

       ....

} else{

       ....

}

1 Answer

0 votes
by (107k points)

In R programming, you can use any() in that pass your condition, kindly refer to the following code:

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

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...