在R

时间:2016-03-04 17:38:29

标签: r permutation

我生成0和1的10元素向量,并将可能的1的数量从2变为9.

例如 2个值= 1

1000000010

3个值= 1

1010100000

编辑:我想有效地生成所有可能的组合。

我有一种粗暴的做法,但我猜测有一种更简单的方法可以使用某种排列函数来实现这一点。

我的方式: 使用R中的sample函数:我从一个全零的向量开始,从1到10绘制2个随机数而不进行替换,并将这些作为向量中元素的索引更改为1.我这样做了很多然后扔掉我们的副本。

mat <- matrix(data = 0,nrow = 1000,ncol = 10) #matrix to hold output
vect <- rep(NA, 1000) 
v0 <- rep(0,10)                              #initial vector of all 0s
for(i in 1:dim(mat)[1]){
  mat[i, sample(1:10, 2)] <- 1

  vect[i] <- paste(mat[i,], collapse = "")   #collapse vector to a string
}

mat[duplicated(vect) !=T,]                       #remove duplicates

这是一个关于这样做的方法,但完成工作。

1 个答案:

答案 0 :(得分:2)

To generate all permutations with 2 ones in a 10 element vector, use combn(10,2) to enumerate all possible position:

t(apply(combn(10,2),2,function(x){ tmp<-rep(0,10); tmp[x]<-1; return(tmp) }))

This returns 45 different permutations same result as the OP's code using sampling but more efficient.