【问题标题】:Appending to a vector in a for-loop of a specific value from a data frame附加到数据帧中特定值的 for 循环中的向量
【发布时间】:2022-01-18 20:38:51
【问题描述】:

我最近在一项非常简单的任务中遇到了问题。因此,我有一个名为 tissue.position 的数据框,其中包含一个 x 位置(在第 5 列中)和一个 y 位置(在第 6 列中)。我只想提取具有特定索引位置的特定元素,而我需要提取的元素位置的索引存储在一个名为index_of_matched 的向量中。我想提取具有这些特定索引的元素以及相应的 x 和 y 位置。我有以下代码:

x_position <- c()
y_position <- c()

for (i in length(index_of_matched)) {
  a = index_of_matched[i]
  x_position <- append(x_position, as.vector(tissue.position[a,5]))
  y_position <- append(y_position, as.vector(tissue.position[a,6]))
}

spatial.data <- data.frame(x_position,y_position)

spatial.data 是我存储特别选择的 x 和 y 坐标的数据框的名称。但是,当我运行代码时,我不知何故只能分别获得一个用于 x 和 y 坐标的元素。当我检查要提取的索引数量时,它大约是 3700,这意味着有问题。输出似乎是坐标的总和。这是输出:

x-position  y-position
22117   19328       

我的代码哪里出错了?提前感谢您的帮助!

【问题讨论】:

  • 如果没有可重现的示例,很难判断,但是,您可以执行 spatial.data &lt;- data.frame(tissue.position[index_of_matched, 5:6]),然后根据需要重命名列。

标签: r dataframe vector append bioinformatics


【解决方案1】:

主要的错误是i in length(index_of_matched) 只是一个数字,而不是遍历一个范围。更正后的版本是 i in seq_along(index_of_matched)

但是,像这样使用 for 循环是不习惯的,因为 R 有更多表达方式来完成同样的事情:

x_position <- tissue.position[index_of_matched, 5]
y_position <- tissue.position[index_of_matched, 6]

spatial.data <- data.frame(x_position,y_position)

或者,既然tissue.position 已经是data.frame,那么简单

spatial.data <- tissue.position[index_of_matched, c(5,6)]

【讨论】:

  • 当然......我完全忘记了你可以在没有for循环的情况下完成这个。我对 R 很陌生,而且我更习惯于 Python,所以我在考虑 Python。谢谢你,非常感谢你的帮助!
猜你喜欢
  • 2016-01-31
  • 2015-04-05
  • 2016-12-19
  • 2021-06-24
  • 2023-03-23
  • 2020-04-25
  • 2017-10-21
  • 2017-05-19
  • 1970-01-01
相关资源
最近更新 更多