-7

I have data frame like this:

     var1                           var2                     result  
 c("apple", "www")            c("apple", "zzz")           "apple" 
 c("dog", "cat", "kkk")       c("cat", "kkk")             "cat", "kkk"

I want to find words that overlap in these two variables(var1 and var2) in dataframe in R.

pogibas
  • 27,303
  • 19
  • 84
  • 117
kiris
  • 13
  • 3

1 Answers1

3

I don't think data.frame() can handle vectors as individual elements, so I used data_frame() from the tibble package:

df <- tibble::data_frame(var1 = list(c("apple", "www"), c("dog", "cat", "kkk")), var2 = list(c("apple", "zzz"), c("cat", "kkk")))

apply function by row, where the function takes the intersection of the first and second list elements:

apply(df, 1, function(x) intersect(x[[1]], x[[2]]))
[[1]]
[1] "apple"

[[2]]
[1] "cat" "kkk"
Milan Valášek
  • 571
  • 3
  • 10