Учитывая, что вы хотите применить функцию для каждого текста в вашем фрейме данных, следующий код должен делать то, что вам нужно:
df <- data.frame(text = c ("Hi this is an example", "Hi this is an example", "Hi this is an example", "Hi this is an example"))
words <- c("this", "is", "an", "example")
df$new_column <- sapply(as.character(df$text), function(x) {
return(paste(intersect(strsplit(x, "\\s")[[1]], words), collapse=" "))
})
print(df$new_column)
И с другим примером data.frame:
df <- data.frame(text = c ("Hi this is an example", "Hi this was an example", "Hi this still is an example", "Hi this is another example"))
words <- c("this", "is", "an", "example")
df$new_column <- sapply(as.character(df$text), function(x) {
return(paste(intersect(strsplit(x, "\\s")[[1]], words), collapse=" "))
})
print(df$new_column)
Надеюсь, это поможет!:)