【问题标题】:what's wrong of this simple for loop?这个简单的 for 循环有什么问题?
【发布时间】:2014-07-14 17:35:15
【问题描述】:

我对这个简单的循环感到很困惑。为什么它不起作用?

set.seed(123)
out1<-data.frame(y1=rbinom(10, 1, 0.3),
                y2=rbinom(10, 1, 0.4),
                y3=rbinom(10, 1, 0.5),
                y4=rbinom(10, 1, 0.6))

out<-NULL

for(i in 1:10){
  out[i, ]<-out1[i, ]
}
Error in out[i, ] <- out1[i, ] : incorrect number of subscripts on matrix

【问题讨论】:

  • out 不是 data.frame,它与out&lt;-out1*0out1', you can fix it replacing outfor 循环将起作用。跨度>
  • out

标签: r for-loop


【解决方案1】:

我宁愿绕道而行,因为使用for 循环创建矩阵会变得非常麻烦(例如,参见Stepwise creation of one big matrix from smaller matrices in R for-loops)。因此,我的解决方案是:

# Prepare emtpy list:
out <- list()

for(i in 1:10){
   # Store everything in list:
   out[[i]]<-out1[i, ]
   # Bind elements rowwise into matrix:
   Z <- do.call(rbind, out)
 }

这将为您提供一个矩阵Z 作为输出,它与原始矩阵out1 相同。您可以通过调用identical(out1, Z) 来验证这一点,这将输出TRUE iff out1Z 相同。

【讨论】:

    【解决方案2】:

    这是修复代码的方法,无需预先分配 out 和 10x4 的 dim()。但是,请注意,使用rbind() 是一种非常低效的编码方式。您应该改为预先分配。

    out1<-data.frame(y1=rbinom(10, 1, 0.3),
                     y2=rbinom(10, 1, 0.4),
                     y3=rbinom(10, 1, 0.5),
                     y4=rbinom(10, 1, 0.6))
    
    out<-NULL
    
    for(i in 1:10){
      out <- rbind(out, out1[i, ])
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-13
      相关资源
      最近更新 更多