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循环不是一种有效的方法。有没有更方便的方法来获得相应的交叉?
答案 0 :(得分:3)
我们可以使用Map
来应用相应元素上的函数
Map(intersect, w1, w2)
#[[1]]
#[1] "apple"
#[[2]]
# character(0)
或使用pmap/map2
purrr
library(purrr)
pmap(list(w1, w2), intersect)