假设我有以下列表:
org <- list(1L, c(1L,2L), 2L, c(1L,3L), c(1L,2L,3L), c(2L,3L), 3L, 4L)
str(org)
#> List of 8
#> $ : int 1
#> $ : int [1:2] 1 2
#> $ : int 2
#> $ : int [1:2] 1 3
#> $ : int [1:3] 1 2 3
#> $ : int [1:2] 2 3
#> $ : int 3
#> $ : int 4
现在我想获取完整列表中的位置。 因此在示例中,位置 1、2、3、4、6、7 都是列表中第 5 个元素的子集。 列表中的第 8 个元素不是列表中其他元素的子集。 所以,我想返回这些元素的位置。在这种情况下:5 和 8。
compl <- c(5, 8)
我可以使用 data.table 轻松实现吗?
由 reprex package 创建于 2021-04-29 (v1.0.0)
最佳答案
这是一个基本的 R 选项:
#Define a function which identifies a complete set
complete_set <- function(x, y) all(x %in% y)
#Check each set with every other set
mat <- sapply(org, function(x) sapply(org, function(y) complete_set(x, y)))
#Turn diagonals to be FALSE
diag(mat) <- FALSE
#position of sets which are not complete
which(colSums(mat) == 0)
#[1] 5 8
这基本上是一个双循环(因此如果列表太大则不是最有效的)。它将列表中的每个元素 ( x
) 与所有其他元素 ( y
) 进行比较并返回 TRUE
如果第一个元素 ( x
) 完全存在于第二个元素 ( y
) 中。由于每个元素都完全独立存在,我们手动将它们转为 FALSE
使用 diag(mat) <- FALSE
.最后,我们只选择那些不完全存在于列表中任何元素中的元素。 (colSums(mat) == 0
)。
https://stackoverflow.com/questions/67314133/