Hope this helps!
library(dplyr)
df %>%
rowwise() %>%
mutate(animals = paste(list_of_words[unlist(
lapply(list_of_words, function(x) grepl(x, text, ignore.case = T)))], collapse=",")) %>%
data.frame()
Output is:
page text animals
1 12 pets: dog & hen hen,dog
2 6 Lions and tigers are dangerous animal tiger,Lion
3 9 I have tried to ride a horse horse
4 65 parrot & crow are very clever birds
Sample data:
df <- structure(list(page = c(12, 6, 9, 65), text = structure(c(4L,
2L, 1L, 3L), .Label = c("I have tried to ride a horse", "Lions and tigers are dangerous animal",
"parrot & crow are very clever birds", "pets: dog & hen"), class = "factor")), .Names = c("page",
"text"), row.names = c(NA, -4L), class = "data.frame")
list_of_words <- c("tiger", "elephant", "rabbit", "hen", "dog", "Lion", "camel", "horse")
Another approach:
library(data.table)
setDT(df)[, animals := paste(list_of_words[unlist(lapply(list_of_words, function(x) grepl(x, text, ignore.case = T)))], collapse = ","), by = 1:nrow(df)]
#> df
# page text animals
#1: 12 pets: dog & hen hen,dog
#2: 6 Lions and tigers are dangerous animal tiger,Lion
#3: 9 I have tried to ride a horse horse
#4: 65 parrot & crow are very clever birds