在R中对矩阵的列进行加权求和的最快方法

9

我需要计算矩阵每一列的加权总和。

data <- matrix(1:2e7,1e7,2) # warning large number, will eat up >100 megs of memory
weights <- 1:1e7/1e5
system.time(colSums(data*weights))
system.time(apply(data,2,function(x) sum(x*weights)))
all.equal(colSums(data*weights), apply(data,2,function(x) sum(x*weights)))

通常情况下,colSums(data*weights)比apply调用更快。我经常执行此操作(在大矩阵上)。因此,寻求最有效的实现建议。理想情况下,如果我们可以将权重传递给colSums(或rowSums),那就太好了。谢谢,感激任何见解!
2个回答

8
colSums*都是内部或原始函数,比apply方法快得多。
另一种方法是尝试使用一些基本的矩阵代数,因为你正在寻找。
 weights %*% data

矩阵乘法方法似乎并不更快,但它可以避免创建一个与 data 大小相同的临时对象。
system.time({.y <- colSums(data * weights)})
##  user  system elapsed 
##  0.12    0.03    0.16 


system.time({.x <- weights %*% data})
##   user  system elapsed 
##   0.20    0.05    0.25 

3

Rcpp可以提高性能(特别是在列数较大的情况下)。

library(Rcpp)
library(inline)
src <- '
 Rcpp::NumericMatrix dataR(data);
 Rcpp::NumericVector weightsR(weights);
 int ncol = dataR.ncol();
 Rcpp::NumericVector sumR(ncol);
 for (int col = 0; col<ncol; col++){
   sumR[col] = Rcpp::sum(dataR( _, col)*weightsR);
 }
 return Rcpp::wrap(sumR);'

weighted.colSums <- cxxfunction(
  signature(data="numeric", weights="numeric"), src, plugin="Rcpp")
data <- matrix(as.numeric(1:1e7),1e5,100) # warning large object
weights <- 1:1e5/1e5
all.equal(colSums(data*weights), weighted.colSums(data, weights))
## [1] TRUE
print(system.time(colSums(data*weights)))
##   user  system elapsed 
##  0.065   0.001   0.064 
print(system.time(as.vector(weighted.colSums(data, weights))))
##   user  system elapsed 
##  0.019   0.001   0.019 
all.equal(as.vector(weights %*% data), weighted.colSums(data, weights))
## [1] TRUE
print(system.time(weights %*% data))
##   user  system elapsed 
##  0.066   0.001   0.066 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接