给定两个字符元素列表:
set.seed(0)
indexes <- list(c("1","2","3"),c("2","3","4"))
> indexes
[[1]]
[1] "1" "2" "3"
[[2]]
[1] "2" "3" "4"
try <- list(as.character(round(rnorm(10,2,2),0)),
as.character(round(rnorm(10,2,2),0)),
as.character(round(rnorm(10,2,2),0)))
> try
[[1]]
[1] "5" "1" "5" "5" "3" "-1" "0" "1" "2" "7"
[[2]]
[1] "4" "0" "0" "1" "1" "1" "3" "0" "3" "0"
[[3]]
[1] "2" "3" "2" "4" "2" "3" "4" "1" "-1" "2"
我想检查try
内每个“子列表”的有多少个字符包含在 indexes
的每个“子列表”中以“成对比较”的方式。
例如:在try[[1]]
中我们有("1","3","1","2")
包含在 indexes[[1]]
内,因此本场比赛的结果将为 4。然后,对于 try[[2]]
之间的匹配和indexes[[1]]
我们有("1","1","1","3","3")
所以这里的结果是 5。 try[[3]]
的推理相同和indexes[[1]]
.
然后我们通过 try[[1]]
之间的匹配和indexes[[2]]
由 ("3","2")
表示,所以这里的结果将是 2,依此类推。
我希望将结果存储在变量中作为输出(参见下面的示例)
我找到了一个可行的解决方案来做到这一点,但我有一个巨大的列表可以应用它(我真正的 try
列表有 400 万个元素,我的 indexes
列表有 100 个元素),所以我在做什么非常慢。
这是我的解决方案:
for(i in 1:length(indexes)){
tmp <- lapply(try,function(x) sum(x %in% indexes[[i]]))
assign(paste0("a",i),tmp)
}
> a1
[[1]]
[1] 4
[[2]]
[1] 5
[[3]]
[1] 7
> a2
[[1]]
[1] 2
[[2]]
[1] 3
[[3]]
[1] 8
最佳答案
如果这仍然太慢,您可能需要考虑使用编译代码来完成它,例如使用 Rpcc。我没有找到使用矢量化函数来做到这一点的方法:
combs <- expand.grid(try = seq_along(try), indexes = seq_along(indexes))
combs$n_match <- mapply(function(i, j, a, b) sum(a[[i]] %in% b[[j]]),
combs[,1], combs[,2],
MoreArgs = list(a = try, b = indexes))
# try indexes n_match
#1 1 1 4
#2 2 1 5
#3 3 1 7
#4 1 2 2
#5 2 2 3
#6 3 2 8
关于r - 快速检查 R 中另一个列表中包含一个列表的多少个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37683295/