![](/img/trans.png)
[英]Keeping elements (from list of vectors) that do not have a proper subset within that list (in R)
[英]Keeping vectors (from list of vectors) whose elements do not have a proper subset within that same list (using RCPP)
我之前問過這個問題(見這里)並使用purr
package 得到了滿意的答案。 然而,這已被證明是我程序中的一個瓶頸,所以我想使用RCPP
package 重寫該部分。
真子集:集合 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。
以前的解決方案
library(purr)
possibilities <- list(a,b,c,d,e,f)
keep(possibilities,
map2_lgl(.x = possibilities,
.y = seq_along(possibilities),
~ !any(map_lgl(possibilities[-.y], function(z) all(z %in% .x)))))
這里的概念是避免 O(N^3) 並使用較少的順序。 這里提供的另一個答案仍然很慢,因為它大於 O(N^2)。 這是一個小於 O(N^2) 的解決方案,當所有元素都是唯一的時,最壞的情況是 O(N^2)。
onlySet <- function(x){
i <- 1
repeat{
y <- sapply(x[-1], function(el)!all(is.element(x[[1]], el)))
if(all(y)){
if(i==length(x)) break
else i <- i+1
}
x <- c(x[-1][y], x[1])
}
x
}
現在要顯示時差,請查看以下內容:
match_fun <- Vectorize(function(s1, s2) all(s1 %in% s2))
method1 <- function(a){
mat <- outer(a, a, match_fun)
a[colSums(mat) == 1]
}
poss <- rep(possibilities, 100)
microbenchmark::microbenchmark(method1(poss), onlySet(poss))
Unit: milliseconds
expr min lq mean median uq max neval cld
method1(poss) 840.7919 880.12635 932.255030 889.36380 923.32555 1420.1077 100 b
onlySet(poss) 1.9845 2.07005 2.191647 2.15945 2.24245 3.3656 100 a
您是否嘗試過首先優化基礎 R 中的解決方案? 例如,以下復制了您預期的 output 並使用(更快)基本 R 數組例程:
match_fun <- Vectorize(function(s1, s2) all(s1 %in% s2))
mat <- outer(possibilities, possibilities, match_fun)
possibilities[colSums(mat) == 1]
#[[1]]
#[1] 1 2
#
#[[2]]
#[1] 1 3
#
#[[3]]
#[1] 2 4
受 Onyambu 高性能解決方案的啟發,這里是另一個使用遞歸 function 的基本 R 選項
f_recursive <- function(x, i = 1) {
if (i > length(x)) return(x)
idx <- which(sapply(x[-i], function(el) all(x[[i]] %in% el))) + 1
if (length(idx) == 0) f_recursive(x, i + 1) else f_recursive(x[-idx], i + 1)
}
f(possibilities)
性能與 Onyambu 的解決方案相當。
poss <- rep(possibilities, 100)
microbenchmark::microbenchmark(
method1(poss),
onlySet(poss),
f_recursive(poss))
#Unit: milliseconds
# expr min lq mean median uq
# method1(poss) 682.558602 710.974831 750.325377 730.627996 765.040976
# onlySet(poss) 1.700646 1.782713 1.870972 1.819820 1.918669
# f_recursive(poss) 1.681120 1.737459 1.884685 1.806384 1.901582
# max neval
# 1200.562889 100
# 2.371646 100
# 3.217013 100
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.