【问题标题】:Writing the results of the for loop编写 for 循环的结果
【发布时间】:2015-12-21 12:44:02
【问题描述】:

我们试图从 for 循环中写入结果。我们尝试使用write.tableas.data.frame等解决方案,但没有成功。我们希望有一个数据框。

目前我们只有循环,它显示大于 50 的矩阵中的年份和值。看起来像这样:

for (i in 1:nrow(dobowe1)) {
  if(dobowe1[i,4]>50) {
    cat(dobowe1[i,"rok"],dobowe1[i,4], "\n")
  }
}

注意:我们的编程工作不多,因此很难从已经提出的问题中使用其他解决方案。

【问题讨论】:

标签: r loops for-loop dataframe


【解决方案1】:

尝试将每个元素保存到向量中,如下所示:

tabela <- numeric(nrow(dobowe1))
for (i in 1:nrow(dobowe1)) {
  if(dobowe1[i,4]>50) {
    tabela[i] <- paste(dobowe1[i,"rok"],dobowe1[i,4])
  }
}
as.data.frame(tabela)

【讨论】:

    【解决方案2】:

    如果您只想直观地检查矩阵的子集,您可以打印出过滤后的子集:

    # create the filter:
    
    > f <- dobowe1[,4] > 50
    
    # use the filter to subset (index) your data.frame:
    
    > dobowe1[f,c("rok", whatever-4th-var-is-called)]
    
    This will automatically print it out. Or you can write it to a file with ?write.table
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多