2
x1 <- c("I like apple", "she enjoys reading")
x2 <- c("he likes apple", "Mike wants to read this book")  
w1 <- strsplit(x1, " ")
w2 <- strsplit(x2, " ")  

I get two lists:

w1  
[[1]]  
[1] "I"      "like"   "apple"  

[[2]]  
[1] "she"      "enjoys" "reading"

w2  
[[1]]  
[1] "he"    "likes"  "apple"

[[2]]  
[1] "Mike"  "wants" "to"    "read"  "this"  "book"  

I want to get

intersect(w1[[1]], w2[[1]])
intersect(w1[[2]], w2[[2]])

Suppose the lengths of w1 and w2 are very large, thus using for loop is not an efficient way. is there any more convenient way to get the corresponding intersect?

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
N.R
  • 37
  • 5

1 Answers1

3

We can use Map for appylying functions on corresponding elements

Map(intersect, w1, w2)
#[[1]]
#[1] "apple"

#[[2]]
# character(0)

Or using pmap/map2 from purrr

library(purrr)
pmap(list(w1, w2), intersect)
akrun
  • 874,273
  • 37
  • 540
  • 662