如何在R中找到列表列表的交集?

时间:2015-09-15 17:19:17

标签: r

说我有三个清单,

> a
[[1]]
     begin end
     3     5
     9     10
     11    14

[[2]]
     begin end
     3     7
     14    18
     19    24

[[3]]
     begin end
     6     9
     14    22
     18    30

我想要找到的是所有“开始”列的交集,因此在这种情况下,所需的输出将类似于

"3" "14"

我知道How to find common elements from multiple vectors?提供的解决方案;但是,此解决方案假定列表的数量是静态的。如果我在这里的列表数量要改变(例如,对于5个列表,每个列表具有相似的柱状布局),我将如何找到交叉点?

2 个答案:

答案 0 :(得分:1)

一种简单的方法是折叠列表元素并使用table来计算它们

# Recreate the data frame
a <- list(
    data.frame(begin = c(3, 9, 11), end = c(5, 10, 14)),
    data.frame(begin = c(3, 14, 19), end = c(7, 18, 24)),
    data.frame(begin = c(6, 14, 18), end = c(9, 22, 30)))

# "Collapse" the begin columns into a vector.
# We use unlist in case the data frames are not all 
# of the same length(thanks @Frank for pointing this out)
a.beg <- unlist(sapply(a, function(x){x$begin}))

# Count the elements
tb <- table(a.beg)

# Get the ones repeated at least twice 
# (need to cast to numeric as names are strings)
intersection <- as.numeric(names(tb[tb>=2]))

> intersection
[1]  3 14

答案 1 :(得分:0)

使用@ nico的输入数据......

full <- do.call(rbind, lapply(seq_along(a), function(i) within(a[[i]], {g = i})) )

res  <- table(full[,c("begin","g")])

#      g
# begin 1 2 3
#    3  1 1 0
#    6  0 0 1
#    9  1 0 0
#    11 1 0 0
#    14 0 1 1
#    18 0 0 1
#    19 0 1 0

行是begin的唯一值,列是列表的元素。要查看begin的哪些值出现在列表的多个元素中,请查看

res[ rowSums( res>0 ) > 1, ]
#      g
# begin 1 2 3
#    3  1 1 0
#    14 0 1 1

无论您需要进行哪些进一步的分析,都应该在full而不是数据框架列表上进行,特别是如果需要考虑效率的话。

相关问题