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]])
假设w1
和w2
的长度非常大,因此使用for循环并不是一种有效的方法。有没有更方便的方法来获取相应的交集?
最佳答案
我们可以使用Map
在相应的元素上应用函数
Map(intersect, w1, w2)
#[[1]]
#[1] "apple"
#[[2]]
# character(0)
或者使用purrr
中的pmap/map2
library(purrr)
pmap(list(w1, w2), intersect)
关于r - 查找两个列表中的常见单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49020454/