【问题标题】:R - how to convert two `for` loops to `lapply`?R - 如何将两个`for`循环转换为`lapply`?
【发布时间】:2017-04-20 14:42:42
【问题描述】:

我有这个代码:

    getSomething = function(x, y) {
      return something
    }

    b = matrix(NA, nrow = ncol(a), ncol = ncol(a))

    # Loop through the columns
    for(i in 1:ncol(a)) {
      # Loop through the columns for each column
      for(j in 1:ncol(a)) {
        b[i, j] = getSomething(as.matrix(a[i]), as.matrix(a[j]))
      }
    }

它工作得很好,但是当我尝试在大数据集上运行代码时,它需要很长时间才能运行。

如何将其转换为lapply函数,使其运行更快?

谢谢。

【问题讨论】:

    标签: r for-loop apply lapply


    【解决方案1】:

    不要使用lapply,而是查看outer,它会为您执行这些循环:

    outer(seq(ncol(a)), seq(ncol(a)),
          FUN=function(i, j) getSomething(as.matrix(a[i]), as.matrix(a[j]))
    )
    

    【讨论】:

    • 感谢您的回答,但我仍然收到错误消息:dims [product 3249] do not match the length of object [1](3249 来自 57 * 57,a 有 57 个变量和 200 个观察值)。我需要考虑a 中的观察次数吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-05
    • 1970-01-01
    • 2022-01-24
    • 2018-03-19
    • 2023-04-01
    • 1970-01-01
    相关资源
    最近更新 更多