【发布时间】: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循环。但我要求提供更多代码,因为编写函数从调用环境中提取整个对象,而意图是对它们进行迭代操作,这通常表明该函数中发生了不好的事情。 -
我不需要迭代地做。可以说,每一行都是“独立的”。