如何改进此功能?
powerset = function(s){
len = length(s)
l = vector(mode="list",length=2^len) ; l[[1]]=numeric()
counter = 1L
for(x in 1L:length(s)){
for(subset in 1L:counter){
counter=counter+1L
l[[counter]] = c(l[[subset]],s[x])
}
}
return(l)
}
测试向量
x <- 1:3
powerset(x)
输出
[[1]]
numeric(0)
[[2]]
[1] 1
[[3]]
[1] 2
[[4]]
[1] 1 2
[[5]]
[1] 3
[[6]]
[1] 1 3
[[7]]
[1] 2 3
[[8]]
[1] 1 2 3
答案 0 :(得分:3)
试试这个:
powerset<-function(s) {
n<-length(s)
do.call(c,lapply(0:n,function(x) combn(s,x,simplify=FALSE)))
}
s<-1:3
powerset(s)
答案 1 :(得分:0)
如果你的矢量非常大,那么来自combnPrim
的gRbase
会更有效率。与@nicola功能相同,但将combn
替换为combnPrim
library(gRbase)
powersetPrim <- function(s) {
n<-length(s)
do.call(c,lapply(0:n,function(x) combnPrim(s,x,simplify=FALSE)))
}
s<-1:3
powersetPrim(s)
较小的样本
s <- 1:25
microbenchmark(powersetPrim(), powerset(), unit='relative', times=10L)
#Unit: relative
# expr min lq mean median uq max neval cld
#powersetPrim() 1.000000 1.00000 1.000000 1.000000 1.000000 1.000000 10 a
# powerset() 5.254663 4.21187 3.644953 3.386665 2.874453 3.844787 10 b