在两个列表中查找常用词

Find common words within two list

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, " ")  

我得到两个列表:

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"  

我想得到

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

假设w1w2的长度非常大,那么使用for循环不是一个有效的方法。有没有更方便的方法得到对应的相交?

我们可以使用Map对相应元素应用函数

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

#[[2]]
# character(0)

或使用 purrr

中的 pmap/map2
library(purrr)
pmap(list(w1, w2), intersect)