R 匹配两个列表并找到匹配的元素
R match two lists and find matching elements
我有两个列表:
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 中的 INTERSECTING 元素,如上所示。
如何解决?代码片段将不胜感激。
谢谢。
我们可以试试嵌套循环。在函数 f1match
中,我们遍历第一个列表 (sapply(list1, function(x)
),拆分每个元素 (strsplit(x, ' ')
),遍历输出并像以前一样拆分 list2 的每个元素,检查是否有list2 的拆分列表元素中的元素在 list1 中,再次检查条件以创建 'TRUE/FALSE' 的逻辑索引。这可以用于通过交换 f1match
中的参数来对 'lst1' 和 'lst2' 进行子集化
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]
我有两个列表:
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 中的 INTERSECTING 元素,如上所示。
如何解决?代码片段将不胜感激。
谢谢。
我们可以试试嵌套循环。在函数 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]