我想在R中订购2个列表,并在最长的2个元素上相交。例如:
Membership1
[[1]]
[1] 3 4 6 7 8
[[2]]
[1] 5 13 23
[[3]]
[1] 1 2 12 14 15 16 18 21 25 28
Membership2
[[1]]
[1] 8 13 20 21 23
[[2]]
[1] 3 6 7
[[3]]
[1] 1 2 4 5 10 15 17 19 24 25 29
这里的结果是:
[[3]]
[1] 1 2 12 14 15 16 18 21 25 28
[[1]]
[1] 3 4 6 7 8
[[2]]
[1] 5 13 23
和
[[3]]
[1] 1 2 4 5 10 15 17 19 24 25 29
[[1]]
[1] 8 13 20 21 23
[[2]]
[1] 3 6 7
然后1, 2, 15, 25
和8
(两个[[3]]
的交叉点)
交叉函数非常简单,但我不明白如何以我想要的方式订购这些列表。
曼努埃尔
答案 0 :(得分:2)
订购清单w.r.t.其元素的长度,非增加,调用:
x <- list(1:5, 1:3, 1:7)
(x <- x[order(sapply(x, length), decreasing=TRUE)])
## [[1]]
## [1] 1 2 3 4 5 6 7
##
## [[2]]
## [1] 1 2 3 4 5
##
## [[3]]
## [1] 1 2 3
因此,整个任务可以用例如:
来解决Membership1 <- list(c(3, 4, 6, 7, 8), c(5, 13, 23), c(1, 2, 12, 14, 15, 16, 18, 21, 25, 28))
Membership2 <- list(c(8, 13, 20, 21, 23), c(3, 6, 7), c(1, 2, 4, 5, 10, 15, 17, 19, 24, 25, 29))
Membership1 <- Membership1[order(sapply(Membership1, length), decreasing=TRUE)]
Membership2 <- Membership2[order(sapply(Membership2, length), decreasing=TRUE)]
lapply(seq_along(Membership1), function(i) intersect(Membership1[[i]], Membership2[[i]]))
## [[1]]
## [1] 1 2 15 25
##
## [[2]]
## [1] 8
##
## [[3]]
## numeric(0)
同样地,正如@flodel建议的那样,最后一步可以按如下方式执行:
Map(intersect, Membership1, Membership2)
甚至:
mapply(intersect, Membership1, Membership2, SIMPLIFY=FALSE)