【问题标题】:Store values from for loop in R在 R 中存储来自 for 循环的值
【发布时间】:2021-01-20 11:59:48
【问题描述】:

我有一个带有脚手架注释的大型数据框(示例行):

 gff <- data.frame(seqid = c("Scaffold21", "Scaffold21", "Scaffold21", "Scaffold31", "Scaffold31", "Scaffold11561", "Scaffold11561"),
                    start = c(4179,16947,18411,25986,45575, 52,54100),
                    end = c(4697,17667,19643,32223,46657,1572,54627),
                    attributes = c("tRNA","sRNA","exon","rRNA","mRNA","mRNA","exon"))

我还有另一个带有 RNA 坐标的数据框(示例行)

RNA <- data.frame(seqid = c("Scaffold21", "Scaffold11561"),
                  start = c(17047,1380))

我一直在尝试过滤第一个数据帧以注释第二个数据帧中的 RNA:

scaffold <- unique(RNA$seqid)
coord <- RNA$start
n <- length(scaffold)*length(coord)
output <- matrix(ncol = ncol(gff), nrow = n)
myfunc <- function(x,y){gff[gff$seqid == x & gff$start <= y & gff$end >= y,]}

for (x in scaffold) {
  for (y in coord) {
    test = myfunc(x, y)
    output <- test
  }
}

这里的问题是只存储了关于最后一个 x,y 对的信息。如果有人能帮我解决这个问题,我将不胜感激。

我现在得到的输出如下所示: |seqid|开始|结束| |:----|:----|:--| |支架11561|52|1572|mRNA|

理想情况下,它看起来像:

seqid start end
Scaffold21 16947 17667
Scaffold11561 52 1572

【问题讨论】:

  • 如果无法访问您的数据,就很难确切知道发生了什么。但在我看来,在 y 循环的每次迭代中,您都在使用 test 覆盖/替换 output。您将输出指定为矩阵(我假设是预期的大小)?因此,在循环中,您还必须指定矩阵中每个值的存储位置。
  • (我添加的玩具数据就像我的整个数据一样工作)是的,这正是正在发生的事情。输出被覆盖,我不知道如何阻止它。我一直无法找到一种方法来指定矩阵中每个值的存储位置。
  • 您可以在内部 for 循环中尝试 i
  • 你能发布你的预期输出吗?
  • @mmn 感谢您的建议,但没有奏效。我收到错误消息:输出错误 [i, ]

标签: r for-loop filter


【解决方案1】:

根据您的示例代码,您可以使用以下代码:

scaffold <- unique(RNA$seqid)
coord <- RNA$start
n <- length(scaffold)*length(coord)
output <- data.frame(matrix(ncol = ncol(gff), nrow = n)) #matrix can only store one type
myfunc <- function(x,y){gff[gff$seqid == x & gff$start <= y & gff$end >= y,]}

i <- 0L


for (x in scaffold) {
  for (y in coord) {
    i <- i + 1L
    test <- myfunc(x, y)
    if(nrow(test) != 1) next
    output[i, ] <- test
  }
}
output <- na.omit(output)

如果有很多行,这可能会很慢。您也可以考虑使用联接。例如:

a<- merge(gff, RNA, by = "seqid")
a[(a$start.x <= a$start.y) & (a$end >= a$start.y),]

【讨论】:

  • 非常感谢!两个建议(尤其是第二个)都非常有效
猜你喜欢
  • 2021-09-10
  • 1970-01-01
  • 2016-08-21
  • 1970-01-01
  • 2016-11-25
  • 2013-12-07
  • 2015-08-25
  • 1970-01-01
  • 2021-07-28
相关资源
最近更新 更多