我有两个列表:
lst1 <- list(c("environmental science", "environmental social science", "nature"), c("bodies of water", "erosion landforms", "valleys"), c("meteorological concepts", "climate", "environmental"), c("fireplaces", "metalworking", "industrial"))
lst2 <- list(c("environmental social", "fragile", "ocean"), c("air", "water", "rain water"), c("day", "astronomy"))
我想保留列表元素的分组,并将 lst1 的元素与 lst2 的元素匹配。例如,本例中所需的答案如下:
[1] "environmental science" "environmental social science" "nature"
在 lst1 和
[1] "meteorological concepts" "climate" "environmental"
在 lst1 中有一些单词与
匹配[1] "environmental social" "fragile" "ocean"
在 lst2 中。
再次
[1] "bodies of water" "erosion landforms" "valleys"
在 lst1 中有一些单词与
匹配[1] "air" "water" "rain water"
在 lst2 中。
因此,所需的答案是 lst1 和 lst2 中的相交元素,如上所示。
如何解决这个问题?代码片段将不胜感激。
谢谢。
最佳答案
我们可以尝试嵌套循环。在函数 f1match
中,我们循环第一个列表 (sapply(list1, function(x)
),分割每个元素 (strsplit(x, ' ')
),循环输出并像以前一样分割list2的每个元素,检查list2的分割列表元素中是否有任何元素在list1中,再次检查条件以创建“TRUE/FALSE”的逻辑索引。可通过交换 f1match
f1match <- function(list1, list2){
sapply(list1, function(x) any(sapply(strsplit(x, ' '), function(y)
any(sapply(list2, function(x1) any(sapply(strsplit(x1, ' '),
function(y1) any(y1 %in% y))))))))
}
indx1 <- f1match(lst1, lst2)
indx2 <- f1match(lst2, lst1)
indx1
#[1] TRUE TRUE TRUE FALSE
indx2
#[1] TRUE TRUE FALSE
lst1[indx1]
lst2[indx2]
关于R 匹配两个列表并找到匹配元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30433246/