【问题标题】:Most computationally efficient method to perform sumproduct for a very large dataframe in R在 R 中为非常大的数据帧执行 sumproduct 的计算效率最高的方法
【发布时间】:2017-11-16 01:44:15
【问题描述】:

我有一个非常大的数据框(数百列和数万行),我想为此执行以下操作:

  • 在每一行上使用给定的权重向量计算列中元素的加权组合(某些权重可能为零)
  • 创建一个新的数据框,每列包含相应权重向量的加权组合

什么是计算效率最高的方法?

复制简单示例:

require(tidyverse)

theDatesTibble <-c(lubridate::mdy("3/15/2017"), lubridate::mdy("4/15/2017"), lubridate::mdy("5/15/2017"), lubridate::mdy("6/15/2017"))

theValuesTibble_A <- c(123.45, 201.29, 337.78, 275.98)
theValuesTibble_B <- c(113.45, 221.29, 327.78, 255.98)
theValuesTibble_C <- c(143.45, 251.29, 307.78, 235.98)
theValuesTibble_D <- c(153.45, 231.29, 347.78, 225.98)
theValuesTibble_E <- c(163.45, 291.29, 323.78, 215.98)

theTibble <- tibble(Dates= theDatesTibble, A = theValuesTibble_A, B = theValuesTibble_B, 
                    C = theValuesTibble_C, D = theValuesTibble_D, E = theValuesTibble_E)

weights_1 <- c(2.3, 0.0, 3.6, 12.7, 8.9)
weights_2 <- c(0.0, 0.0, 13.6, 4.7, 0.0)
weights_3 <- c(6.3, 4.4, 8.6, 12.3, 18.9)

【问题讨论】:

  • 在我看来像矩阵产品...

标签: r performance


【解决方案1】:

正如@BenoitLondon 所提到的,矩阵乘积将是实现您想要的最快的方法。

cbind.data.frame(
  theTibble[1],
  as.matrix(theTibble[-1]) %*% cbind(weights_1, weights_2, weights_3)
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-10
    • 2016-09-11
    • 2015-04-30
    • 2014-01-23
    • 1970-01-01
    • 1970-01-01
    • 2021-07-31
    • 2014-09-23
    相关资源
    最近更新 更多