作者gsuper (统计的巴比伦塔)
看板Statistics
标题[程式] 排列组合的加法
时间Mon Dec 20 01:20:17 2010
我需要算的原始资料如下
x <- c(1,2,4)
然後要能够算出所有排列组合的加法
result
---------------
1=1
2=2
4=4
3=1+2
5=1+4
6=2+4
7=1+2+4
---------------
请问有没有现成的 function 可以用?
如果没有的话
这种东西大概要怎麽写阿?
--
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 140.113.239.247
※ 编辑: gsuper 来自: 140.113.239.247 (12/20 01:20)
自问自答 again
x <- c(1,2,4)
i=1
S_list<-NULL
for(i in 1:length(x))
{ S_list[[i]] <-
combn(x,m=i) }
※ 编辑: gsuper 来自: 140.113.239.247 (12/20 16:08)
※ 编辑: gsuper 来自: 140.113.239.247 (12/20 16:08)
1F:→ andrew43:厉害 12/20 18:27
2F:→ bmka:可以用sapply避免写loop 12/20 20:34
写了一个递回版本
看起来跟回圈一样慢
终端机萤幕都要闪12下 (12秒)
不知道还有没有办法写的更快
#################################
x <- 1:20
a=NULL
i=length(x)
fx <- function(tmp)
{
a[[i]] <<- combn(tmp,m=i)
i <<- i-1
if(i!=0){fx(tmp)}
}
fx(x)
※ 编辑: gsuper 来自: 140.113.239.247 (12/21 01:24)
※ 编辑: gsuper 来自: 140.113.56.120 (12/21 02:40)
※ 编辑: gsuper 来自: 140.113.56.120 (12/21 03:09)
## apply 版本也是12秒
x <- 1:20
i = matrix(1:length(x),length(x),1)
fx <- function(I)
{combn(x,m=I)}
a <- apply(i,1,fx)
※ 编辑: gsuper 来自: 140.113.239.247 (12/21 20:45)
※ 编辑: gsuper 来自: 140.113.239.247 (12/21 20:45)
3F:→ bmka:sapply(1:20, combn, x=1:20) should yield the same result 12/21 21:43
测试完还是12秒
我想是 combn() 的速度上限影响的吧
P.S. 这个写法很酷
4F:→ lin15:apply系列似乎不会比较快喔~ 12/21 21:48
※ 编辑: gsuper 来自: 140.113.239.247 (12/21 21:58)
※ 编辑: gsuper 来自: 140.113.239.247 (12/21 22:23)
※ 编辑: gsuper 来自: 140.113.239.247 (12/21 22:37)
又当笔记用了...
这是整理成 index 的做法
F <- 14
data <- sapply(1:F, combn, x=1:F)
fx<-function(M)
{ if(dim(M)[1]!=F)
M <- rbind(M,matrix(0,F-dim(M)[1],dim(M)[2]))
}
data <- sapply(data,fx)
DATA <- NULL
for(g in 1:F)
{ DATA <- cbind(DATA,data[[g]]) }
※ 编辑: gsuper 来自: 140.113.239.247 (06/08 14:44)
##########################################################
require(combinat)
permn(3)
combn(3, 2)
※ 编辑: gsuper (114.32.215.136), 07/29/2014 16:49:16