【问题标题】:R function with loop append avoiding for (using lapply instead)带有循环附加避免 for 的 R 函数(使用 lapply 代替)
【发布时间】:2016-11-26 13:45:43
【问题描述】:

我听说不建议在 R 中使用 for 循环,主要是因为它很慢。我听说我应该改用 lapply,因为它调用 C 是为了提高效率。

问题:能否告诉我如何将以下示例转换为lapply 高效代码(或同一家族的任何其他apply sapply)?

myFun <- function(loop){
  result = data.frame() #init new df
  for(iteration in 1:loop){
    generateRnorm1 = matrix(data = rnorm(n = 1000000), nrow = 10000, ncol = 10000)
    generateRnorm2 = matrix(data = rnorm(n = 1000000), nrow = 10000, ncol = 10000)
    iterationResult = sum(generateRnorm1, generateRnorm2)
    bindIterationResult = cbind(iteration, iterationResult)
    result = rbind(result, bindIterationResult)
  }
  return(result)
}

test = myFun(loop = 10)

【问题讨论】:

标签: r function functional-programming lapply


【解决方案1】:

这是一个lapply 方法:

myFun2 <- function(loop){
  generateRnorm1 = matrix(data = rnorm(n = 1000000), nrow = 10000, ncol = 10000)
  generateRnorm2 = matrix(data = rnorm(n = 1000000), nrow = 10000, ncol = 10000)
  sum(generateRnorm1, generateRnorm2)
}

# run function over 1:10
myList <- lapply(seq.int(10), myFun2)
# rbind the resulting list
result2 <- do.call(rbind, myList)

请注意,速度并没有太大(如果有的话)提高,因为您的函数主体需要很长时间才能执行。这淹没了lapply 的任何潜在加速。

在我的电脑上,这两种方法都需要大约 20 秒才能运行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-10
    • 1970-01-01
    相关资源
    最近更新 更多