【问题标题】:trouble with apply statement in RR中的apply语句有问题
【发布时间】:2013-04-13 23:11:02
【问题描述】:

我想使用 apply 语句对 R 中数据框的每一行做一些事情。

以下工作我用一堆参数和索引 i 调用函数“calc.Sphere.Metrics”。我将结果存储在每一行中。

for(i in 1: dim(position.matrix)[1]){
   results.obs[i,] <- calc.Sphere.Metrics(i, culled.mutation.data, position.matrix, protein.metrics, radius) 
 }

我尝试了几个 apply、mapply 语句,但都没有运气。这样做的正确方法是什么?

编辑: 根据要求,这是 calc.Sphere.Metrics 的骨架

calc.Sphere.Metrics <- function(index, culled.mutation.data, position.matrix, protein.metrics, radius){
  results <- matrix(data = 0, nrow = 1, ncol = 8)
  colnames(results) <- c("Line.Length","Center", "Start","End","Positions","MutsCount","P.Value", "Within.Range")
  results <- as.data.frame(results)

 ....
 look up a bunch of stuff and fill in each column of results. All the data required is in the parameters passed in and the index.  
 .....
 return(results)
}

Results 的列数与 top 函数中的 results.obs 相同。希望这会有所帮助!

谢谢!

【问题讨论】:

  • 我们可能需要更多细节才能提供帮助。可能是calc.Sphere.Metrics 的完整内容。
  • calc shere metrics 有点令人困惑,但它的作用是获取索引 i,在其他参数(如 mutation.data、position.matrix 等)中查找特定值,然后返回一个数据框1行8列的结果(与results.obs完全相同)。
  • 为什么只有骨架?真的太长了吗?我们希望一切都可以矢量化。
  • Matthew 的回答可能会直接替代您的 for 循环。但我要求提供更多代码,因为编写函数从调用环境中提取整个对象,而意图是对它们进行迭代操作,这通常表明该函数中发生了不好的事情。
  • 我不需要迭代地做。可以说,每一行都是“独立的”。

标签: r apply


【解决方案1】:

大概是这样的:

result.obs <- do.call(rbind, lapply(seq_len(dim(position_matrix)[1]),
    calc.Sphere.Metrics, culled.mutation.data, position.matrix, protein.metrics, radius))

【讨论】:

  • 这很接近,但是因为 calc.Sphere.Metrics 返回一个 1 行 8 列的数据框,所以创建的结果列表不清楚。不过,来自 calc.Sphere.Metrics 的每个返回格式都正确。
  • 最后,这行得通。不过,您让我走上了正确的道路,谢谢! as.data.frame(t(sapply(seq(position.matrix[,2]), calc.Sphere.Metrics, culled.mutation.data, position.matrix, protein.metrics, radius)))
猜你喜欢
  • 2015-05-08
  • 1970-01-01
  • 1970-01-01
  • 2017-11-27
  • 2016-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-04
相关资源
最近更新 更多