![](/img/trans.png)
[英]Keeping vectors (from list of vectors) whose elements do not have a proper subset within that same list (using RCPP)
[英]Keeping elements (from list of vectors) that do not have a proper subset within that list (in R)
真子集:集合 S 的真子集 S' 是严格包含在 S 中的子集,因此排除 S 本身(注意我也排除了空集)。
假设您在列表中有以下向量:
a = c(1,2)
b = c(1,3)
c = c(2,4)
d = c(1,2,3,4)
e = c(2,4,5)
f = c(1,2,3)
我的目标是只保留列表中没有适当子集的向量,在这个例子中是 a、b 和 c。 以下代码是我的解决方案,
possibilities = list(a,b,c,d,e,f)
final.list <- possibilities
for (i in possibilities) {
for (j in rev(possibilities)) {
if (all(i %in% j) & !all(j %in% i)) {
final.list <- final.list[!(final.list %in% list(j))]
} else {
final.list <- final.list
}
}
}
这给出了预期的输出,尽管我担心这种方法的可扩展性。 有没有人有更有效的方法的想法? 谢谢!
* 请注意,就我的真正目的而言,可能性列表的长度——及其子向量——可能会变得非常大。
一种purrr
选项可能是:
map2(.x = possibilities,
.y = seq_along(possibilities),
~ !any(map_lgl(possibilities[-.y], function(z) all(z %in% .x))))
[[1]]
[1] TRUE
[[2]]
[1] TRUE
[[3]]
[1] TRUE
[[4]]
[1] FALSE
[[5]]
[1] FALSE
[[6]]
[1] FALSE
只保留目标向量:
keep(possibilities,
map2_lgl(.x = possibilities,
.y = seq_along(possibilities),
~ !any(map_lgl(possibilities[-.y], function(z) all(z %in% .x)))))
[[1]]
[1] 1 2
[[2]]
[1] 1 3
[[3]]
[1] 2 4
这是一个基本的 R 选项
final.list <- subset(
possibilities,
sapply(
seq_along(possibilities),
function(k) {
!any(sapply(
possibilities[-k],
function(v) all(v %in% possibilities[[k]]) & length(v) < length(possibilities[[k]])
))
}
)
)
这使
> final.list
[[1]]
[1] 1 2
[[2]]
[1] 1 3
[[3]]
[1] 2 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.