我有一个函数可以创建一个给定k和n值的矩阵。每个行组合加起来是k, n是列数。示例:如果k=3, n=20,则
library(partitions)
posloc<- function(k, n){
df = t(as.matrix(blockparts(rep(k,n),k, include.fewer = FALSE)))
indx <- !duplicated(t(apply(df, 1, sort)))
(df[indx, ])
}
posloc(4,5)
[,1] [,2] [,3] [,4] [,5]
[1,] 4 0 0 0 0
[2,] 3 1 0 0 0
[3,] 2 2 0 0 0
[4,] 2 1 1 0 0
[5,] 1 1 1 1 0
我需要将k:0之前的所有矩阵附加到一个矩阵中。例如,我希望最终的矩阵是这样的
[,1] [,2] [,3] [,4] [,5]
[1,] 4 0 0 0 0
[2,] 3 1 0 0 0
[3,] 2 2 0 0 0
[4,] 2 1 1 0 0
[5,] 1 1 1 1 0
[6,] 3 0 0 0 0
[7,] 2 1 0 0 0
[8,] 1 1 1 0 0
[9,] 2 0 0 0 0
[10,] 1 1 0 0 0
[11,] 1 0 0 0 0
[12,] 0 0 0 0 0
我已经尝试了以下,但我总是以只包含最后一行的矩阵结束
for(i in k:0){
assign(paste0("pc_", i), posloc(i,n))
}
for(i in k:0){
temp <- rbind(get(eval(paste0("pc_", i, sep=""))))
}
[,1] [,2] [,3] [,4] [,5]
[1,] 0 0 0 0 0
有人能帮我弄清楚我做错了什么,得到我想要的矩阵?谢谢你。
使用sapply
.
do.call(rbind, sapply(4:0, function(k) posloc(k, 5)))
# [,1] [,2] [,3] [,4] [,5]
# [1,] 4 0 0 0 0
# [2,] 3 1 0 0 0
# [3,] 2 2 0 0 0
# [4,] 2 1 1 0 0
# [5,] 1 1 1 1 0
# [6,] 3 0 0 0 0
# [7,] 2 1 0 0 0
# [8,] 1 1 1 0 0
# [9,] 2 0 0 0 0
# [10,] 1 1 0 0 0
# [11,] 1 0 0 0 0
# [12,] 0 0 0 0 0
如果你想坚持for
循环,你应该首先初始化一个空矩阵。
m <- matrix(nrow=0, ncol=5)
for (i in 4:0) {
m <- rbind(m, posloc(i, 5))
}
# [,1] [,2] [,3] [,4] [,5]
# [1,] 4 0 0 0 0
# [2,] 3 1 0 0 0
# [3,] 2 2 0 0 0
# [4,] 2 1 1 0 0
# [5,] 1 1 1 1 0
# [6,] 3 0 0 0 0
# [7,] 2 1 0 0 0
# [8,] 1 1 1 0 0
# [9,] 2 0 0 0 0
# [10,] 1 1 0 0 0
# [11,] 1 0 0 0 0
# [12,] 0 0 0 0 0