【问题标题】:Let a for loop add all results to an existing data.frame让 for 循环将所有结果添加到现有的 data.frame
【发布时间】:2015-05-05 08:15:29
【问题描述】:

我希望将我的 for 循环生成的结果传递给一个 data.frame。因此我像这样创建了一个空的data.frame:

result <- data.frame(matrix(ncol = 8, nrow = 1))

然后将列名与data.frame的名称进行匹配,即将被搜索:

names(result) <- names(example)

我的 for 循环应该遍历一个值列表并检查输入 data.frame 是否有满足条件的值,然后将此值的整行添加到我的空 data.frame

lpos
[1] 5

for(i in lpos){
indx <- sapply(example[,4], function(x) (x > minpos[i]) & (x < maxpos[i])) 
newrow <- example[indx,]
result = rbind(result, newrow)
}

所以我的预期输出是我得到了一个data.frame,包含所有结果。但似乎这段代码每次都会覆盖添加的行,而我刚刚将最后一次迭代保存在我的 data.frame 中。

如何防止此代码覆盖现有结果? 所以我的数据看起来像这样:

> head(example[1:4,-9])
      V1       V2   V3    V4    V5   V6 V7 V8
1 Spenn-ch00 AUGUSTUS mRNA  5691  9072 0.84  -  .
2 Spenn-ch00 AUGUSTUS mRNA 11246 12192 0.17  -  .
3 Spenn-ch00 AUGUSTUS mRNA 12799 15702 0.33  -  .
4 Spenn-ch00 AUGUSTUS mRNA 15752 18482 0.48  -  .

【问题讨论】:

  • 为什么在循环中使用O,容易误读为0 零。
  • 请将head(example)dput(example) 的输出添加到帖子中,以便我们了解您的数据。也许你可以完全避免 for 循环。
  • 我认为您正在寻找合并范围 - 请参阅 example on mergeByOverlaps
  • 所以我发布了我的data.frame 的负责人。是的,这看起来对我来说是正确的!
  • 看起来你只需要更改为for(i in 1 : lpos){... -- 还是lpos 是一个向量?更多细节会有所帮助。

标签: r for-loop dataframe rbind


【解决方案1】:

问题是我只取了lpos中包含的一个数字,而不是使用从1到lpos的范围

lpos
[1] 5

for(i in 1:lpos){
indx <- sapply(example[,4], function(x) (x > minpos[i]) & (x < maxpos[i])) 
newrow <- example[indx,]
result = rbind(result, newrow)
}

当代码现在这样时,它可以完美运行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-13
    • 1970-01-01
    相关资源
    最近更新 更多