我想对一个由数字向量组成的列进行操作,想知道最佳的方法是什么。
目前我尝试了以下方法,似乎集合方式是最好的,但也许我错过了一些更好的方法来处理它? 如果使用C++处理这个问题,可以期望获得多大的速度提升?
结果如下:
目前我尝试了以下方法,似乎集合方式是最好的,但也许我错过了一些更好的方法来处理它? 如果使用C++处理这个问题,可以期望获得多大的速度提升?
testVector <- data.table::data.table(A = lapply(1:10^5, function(x) runif(100)))
microbenchmark::microbenchmark(lapply = testVector[, B := lapply(A, diff)],
map = testVector[, C := Map(diff, A)],
set = set(testVector, NULL, "D", lapply(testVector[["A"]], diff)),
forset = {for(i in seq(nrow(testVector))) set(testVector, i, "E", list(list(diff(testVector[[i, "A"]]))))},
times = 10L)
结果如下:
Unit: milliseconds
expr min lq mean median uq max neval
set 789.7967 924.8178 1031.923 1082.325 1146.306 1174.671 10
lapply 1122.2454 1468.9556 1563.002 1619.668 1692.217 1919.405 10
map 1297.5236 1320.7022 1571.344 1592.176 1695.673 2012.051 10
forset 1887.0003 2023.7357 2139.202 2174.912 2245.943 2396.844 10
更新
我已经检查了Rcpp在任务中的表现。尽管我的C++技能非常糟糕,但速度提高了>10倍。
C++代码:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
List cppDiff(List column){
int cSize = column.size();
List outputColumn(cSize, NumericVector());
for(int i = 0; i < cSize; ++i){
NumericVector vectorElement = column[i];
outputColumn[i] = Rcpp::diff(vectorElement);
}
return(outputColumn);
}
测试代码:
library(Rcpp);library(data.table);library(microbenchmark)
sourceCpp("diffColumn.cpp")
vLen <- 100L
cNum <- 1e4L
test <- data.table(A = lapply(1L:cNum, function(x) runif(vLen)))
throughMatrix <- function(column){
difmat <- diff(matrix(unlist(column), nrow = vLen, ncol = cNum))
lapply(seq(cNum), function(i) difmat[, i])
}
microbenchmark::microbenchmark(DT = set(test, NULL, "B", lapply(test[["A"]], diff)),
mat = set(test, NULL, "C", throughMatrix(test[["A"]])),
cpp = set(test, NULL, "D", cppDiff(test[["A"]])),
times = 5)
> all.equal(test$B, test$C)
[1] TRUE
> all.equal(test$B, test$D)
[1] TRUE
Unit: milliseconds
expr min lq mean median uq max neval
DT 845.04418 912.60961 1024.79183 1011.59417 1107.14306 1323.9963 10
mat 643.02187 663.92700 778.91145 816.95972 844.37206 864.1173 10
cpp 45.28504 49.35746 84.27799 78.32085 84.87942 226.1347 10
还有一个 10000 x 10000 列的基准测试:
Unit: milliseconds
expr min lq mean median uq max neval
DT 7851.4352 8504.3501 21632.018 25246.7860 29133.358 37424.163 5
mat 8679.9386 8724.1497 22852.724 18235.7693 39199.966 39423.794 5
cpp 244.8572 247.7443 1439.011 303.2556 2715.643 3683.552 5
testVector[, B := lapply(A, function(x) x - shift(x, fill = x[1]))]
- akrun