我有一个向量列表,说:
li <- list( c(1, 2, 3),
c(1, 2, 3, 4),
c(2, 3, 4),
c(5, 6, 7, 8, 9, 10, 11, 12),
numeric(0),
c(5, 6, 7, 8, 9, 10, 11, 12, 13)
)
Run Code Online (Sandbox Code Playgroud)
我想删除已经包含在其他(更大或相等)的所有向量,以及所有空向量
在这种情况下,我只剩下列表
1 2 3 4
5 6 7 8 9 10 11 12 13
Run Code Online (Sandbox Code Playgroud)
实现这一目标是否有任何有用的功能?
提前致谢
首先,您应该按向量长度对列表进行排序,以便在切除循环中保证每个较低索引向量都比每个较高索引向量短,因此setdiff()
您只需要单向。
l <- list(1:3, 1:4, 2:4, 5:12, double(), 5:13 );
ls <- l[order(sapply(l,length))];
i <- 1; while (i <= length(ls)-1) if (length(ls[[i]]) == 0 || any(sapply((i+1):length(ls),function(i2) length(setdiff(ls[[i]],ls[[i2]]))) == 0)) ls[[i]] <- NULL else i <- i+1;
ls;
## [[1]]
## [1] 1 2 3 4
##
## [[2]]
## [1] 5 6 7 8 9 10 11 12 13
Run Code Online (Sandbox Code Playgroud)
any(sapply(...))
这里有一个小的替代方案,用第二个 while 循环替换。优点是,如果 while 循环在列表的其余部分中发现任何超集,它可能会提前中断。
l <- list(1:3, 1:4, 2:4, 5:12, double(), 5:13 );
ls <- l[order(sapply(l,length))];
i <- 1; while (i <= length(ls)-1) if (length(ls[[i]]) == 0 || { j <- i+1; res <- F; while (j <= length(ls)) if (length(setdiff(ls[[i]],ls[[j]])) == 0) { res <- T; break; } else j <- j+1; res; }) ls[[i]] <- NULL else i <- i+1;
ls;
## [[1]]
## [1] 1 2 3 4
##
## [[2]]
## [1] 5 6 7 8 9 10 11 12 13
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
133 次 |
最近记录: |