对于R中的非常大的数据帧执行sumproduct的大多数计算上有效的方法

时间:2017-11-15 16:52:53

标签: r performance

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

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

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

复制简单示例:

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)

1 个答案:

答案 0 :(得分:1)

正如@BenoitLondon所提到的,矩阵产品将是你做你想做的最快的方式。

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