我想将循环中的矢量结果存储到矩阵中,但我不知道行数。例如,以下代码将说明我想要做的事情:
result_final <- c()
for (i in 1:5){
n <- sample(1:5,1) #get the number of rows for this iteration
result_this_time <- matrix(0,n,3) #generate a matrix with row number
#are unknown before running the iteration
#combine all the results from each iteration together
if (i == 1) result_final <- result_this_time
else result_final <- rbind(result_final,result_this_time)
}
result_final
以上代码适合我。问题是它有点复杂。如您所见,当我使用c()
生成新向量时,我不必指示向量的长度。代码test1 <- c();test1[3]<-1
不会报告任何错误,但代码test2 <- matrix();test2[3,3]<-1
会报错,因为它引用了错误的下标。所以我想知道无论如何我可以创建一个“矩阵”,我没有必要明确指出矩阵行(就像使用c()
创建一个向量)来摆脱{{1}声明。
答案 0 :(得分:0)
我使用lapply()
。外部lapply()
控制整体重复,而内部lapply()
执行n
指定的行数。 do.call()
用于简化和绑定(rbind()
)元素。与下面的原始代码进行比较。
set.seed(1237)
# outer loop controls overall repetition
do.call(rbind, lapply(1:5, function(x) {
n <- sample(1:5, 1)
# inner loop control individual rows by n
do.call(rbind, lapply(1:n, function(y) rbind(rep(0, 3))))
}))
[,1] [,2] [,3]
[1,] 0 0 0
[2,] 0 0 0
[3,] 0 0 0
[4,] 0 0 0
[5,] 0 0 0
[6,] 0 0 0
[7,] 0 0 0
[8,] 0 0 0
[9,] 0 0 0
[10,] 0 0 0
set.seed(1237)
result_final <- c()
for (i in 1:5){
n <- sample(1:5,1) #get the number of rows for this iteration
result_this_time <- matrix(0,n,3) #generate a matrix with row number
#are unknown before running the iteration
#combine all the results from each iteration together
if (i == 1) result_final <- result_this_time
else result_final <- rbind(result_final,result_this_time)
}
result_final
[,1] [,2] [,3]
[1,] 0 0 0
[2,] 0 0 0
[3,] 0 0 0
[4,] 0 0 0
[5,] 0 0 0
[6,] 0 0 0
[7,] 0 0 0
[8,] 0 0 0
[9,] 0 0 0
[10,] 0 0 0