Say we have these two vectors:
vowels <- c("a", "e", "i", "o", "u", "y")
word <- c("c", "a", "t")
Is there a simple way to check if word
contains at least one element from vowels
and return either TRUE
or FALSE
?
CodePudding user response:
In base R, you can try:
any(word %in% vowels)
# TRUE
Which first creates a vector of boolean values (TRUE
or FALSE
):
word %in% vowels
# [1] FALSE TRUE FALSE
and then evaluates that vector to see if any of them are true (via any
)
That is by far the easiest, but for other applications you could also use grepl
which returns a vector of TRUE
or FALSE
grepl(paste(vowels, collapse = "|"), word)
# [1] FALSE TRUE FALSE
# Thus
any(grepl(paste(vowels, collapse = "|"), word))
# [1] TRUE