Is it possible to use a grepl argument when referring to a list of values, maybe using the %in% operator? I want to take the data below and if the animal name has "dog" or "cat" in it, I want to return a certain value, say, "keep"; if it doesn't have "dog" or "cat", I want to return "discard".
data <- data.frame(animal = sample(c("cat","dog","bird", 'doggy','kittycat'), 50, replace = T))
Now, if I were just to do this by strictly matching values, say, "cat" and "dog', I could use the following approach:
matches <- c("cat","dog")
data$keep <- ifelse(data$animal %in% matches, "Keep", "Discard")
But using grep or grepl only refers to the first argument in the list:
data$keep <- ifelse(grepl(matches, data$animal), "Keep","Discard")
returns
Warning message:
In grepl(matches, data$animal) :
argument 'pattern' has length > 1 and only the first element will be used
Note, I saw this thread in my search, but this doesn't appear to work:
grep using a character vector with multiple patterns
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…