运行 在 R 中尝试使用应用而不是 for 循环执行任务时内存不足

Running out of memory when trying to perform task with apply rather than for loop in R

我正在尝试重写一些旧代码以使其更有效率。我在我的地方读到使用 apply 应该比使用 for 循环更快,所以我尝试这样做。首先是旧的工作代码:

dl=data.frame(replicate(16,1:15685849))
#in line below mean was sums, but this gave integer overflows. This is not the case in the real dataset, but for the purpose of this example mean will do.
sums<-mapply(mean, dl[,4:ncol(dl)], USE.NAMES=FALSE)
appel<-dl[,1:3]
for (i in 1:(ncol(dl)-3)){
  appel[,i+3]=dl[,i+3]/sums[i]
}

目前没有问题。我试图将这段代码重写为一个函数,这样我就可以制作一个 R 包供私人使用。这是我的尝试

dl=data.frame(replicate(16,1:15685849))
depthnormalise=function(tonormtable, skipleftcol=3){
    sums<-mapply(mean, dl[,4:ncol(dl)], USE.NAMES=FALSE)
    dn=function(x){x/sums}
    tonormtable[,(skipleftcol+1):ncol(tonormtable)]=t(apply(tonormtable[,(skipleftcol+1):ncol(tonormtable)], 1, dn))
}
appel=depthnormalise(dl)

但这会让我运行失去记忆。

我使用应用的经验很少,但我似乎无法正确理解 table 我想保留前 3 列,只更改之后的列.如果需要更多信息,请在投票前告诉我!如果你只投反对票,我不会变得更好。

这是一个可行的 apply 解决方案:

appel1 <- as.matrix(dl)
appel1[, -(1:3)] <- apply(appel1[, -(1:3)], 2, 
                          function(x) round(x / mean(x) * 1e6, digits=2))
all.equal(as.matrix(appel), appel1)
#[1] TRUE

但是,正如评论中所说,它不会比编写良好的 for 循环更快。它在我的系统上比较慢。