I am having trouble with the following scenario. I have a dataframe df
that has multi-word strings in var1
. I want to keep only the words from var1
if that word is in chr
. For example, the first row of var1
has "car tv dog" and I want to delete the word "dog" because it is not in chr
.
My dataframe:
id <- c(1,2,3)
var1 <- c("car tv dog","cat water mouse","pen wire fish")
df <- data.frame(id,var1)
Words I want to keep:
chr<-"car aaa bbb ccc ddd qqq www eee rrr pen cat ttt fish tv"
Desired result:
want <- c("car tv","cat","pen fish")
dfWant <- data.frame(id, var1, want)
Any help will be much appreciated.