【问题标题】:Store vector result from a loop into matrix when the dimension in unkown in R将循环中的向量结果存储到矩阵中,然后存储 R 中未知的维度
【发布时间】: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 &lt;- c();test1[3]&lt;-1 不会报错,但代码test2 &lt;- matrix();test2[3,3]&lt;-1 会报错,因为引用错误的下标。所以我想知道我是否可以创建一个“矩阵”,我不必明确指出矩阵的行(就像使用c() 创建一个向量一样)以摆脱if 语句。

【问题讨论】:

  • 你能解释一下你想要完成的事情吗? test2 &lt;- matrix();test2[3,3]&lt;-1 中的错误是 matrix() 创建了一个 1x1 矩阵,其 NA 在 [1, 1]。您正在描述或试图摆脱的复杂部分是什么?什么是test1? “result_this_time”的占位符?
  • 我想摆脱 if statement 。当您想将结果存储到向量中时,您可以使用c() 来创建新向量,而无需知道维度。当您不知道所需向量的长度时,这真的很方便。但是对于矩阵,它不起作用。如果要将作为向量的结果存储为矩阵的行,则必须知道之前的行数。但是在我的例子中,你不知道你需要多少行。

标签: r matrix vector


【解决方案1】:

与上面的答案类似,创建一个列表来存储您的结果,然后将它们绑定在一起。

result_list <- list()
for(i in 1:5){
  n <- sample(1:5, 1)
  result_list[[i]] <- matrix(0, n, 3)
}
result_final <- do.call(rbind, result_list)

【讨论】:

    【解决方案2】:

    我会使用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
    

    【讨论】:

      猜你喜欢
      • 2017-01-26
      • 2021-01-03
      • 1970-01-01
      • 2015-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多