【发布时间】:2015-05-03 00:23:47
【问题描述】:
我想将循环中的向量结果存储到矩阵中,但我不知道行数。例如,下面的代码将说明我想要做什么:
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() 创建一个向量一样)以摆脱if 语句。
【问题讨论】:
-
你能解释一下你想要完成的事情吗?
test2 <- matrix();test2[3,3]<-1中的错误是 matrix() 创建了一个 1x1 矩阵,其 NA 在 [1, 1]。您正在描述或试图摆脱的复杂部分是什么?什么是test1? “result_this_time”的占位符? -
我想摆脱
if statement。当您想将结果存储到向量中时,您可以使用c()来创建新向量,而无需知道维度。当您不知道所需向量的长度时,这真的很方便。但是对于矩阵,它不起作用。如果要将作为向量的结果存储为矩阵的行,则必须知道之前的行数。但是在我的例子中,你不知道你需要多少行。