我正在寻找C ++ / Rcpp / Eigen或Armadillo中R函数rowsum
的快速替代品。
目的是根据分组向量a
获取向量b
中的元素总和。例如:
> a
[1] 2 2 2 2 2 2 2 2 2 2
> b
[1] 1 1 1 1 1 2 2 2 2 2
> rowsum(a,b)
[,1]
1 10
2 10
在Rcpp
中编写一个简单的for循环非常慢,但也许我的代码效率很低。
我还尝试在rowsum
中调用函数Rcpp
,但rowsum
速度不是很快。
答案 0 :(得分:5)
不是答案,但可能有助于解决问题。看起来像最坏情况的表现是总结许多短群,这似乎与矢量的大小线性缩放
> n = 100000; x = runif(n); f = sample(n/2, n, TRUE)
> system.time(rowsum(x, f))
user system elapsed
0.228 0.000 0.229
> n = 1000000; x = runif(n); f = sample(n/2, n, TRUE)
> system.time(rowsum(x, f))
user system elapsed
1.468 0.040 1.514
> n = 10000000; x = runif(n); f = sample(n/2, n, TRUE)
> system.time(rowsum(x, f))
user system elapsed
17.369 0.748 18.166
似乎有两个捷径,避免重新订购
> n = 10000000; x = runif(n); f = sample(n/2, n, TRUE)
> system.time(rowsum(x, f, reorder=FALSE))
user system elapsed
16.501 0.476 17.025
并避免内部强制角色
> n = 10000000; x = runif(n); f = as.character(sample(n/2, n, TRUE));
> system.time(rowsum(x, f, reorder=FALSE))
user system elapsed
8.652 0.268 8.949
然后是似乎涉及的基本操作 - 计算分组因子的唯一值(预分配结果向量)并进行求和
> n = 10000000; x = runif(n); f = sample(n/2, n, TRUE)
> system.time({ t = tabulate(f); sum(x) })
user system elapsed
0.640 0.000 0.643
所以是的,似乎有一个更快的单一用途实现的范围。这对于data.table
来说似乎很自然,并且在C中实现起来并不太难。这是一个混合解决方案,使用R来制表和“经典”C接口来实现总和
library(inline)
rowsum1.1 <- function(x, f) {
t <- tabulate(f)
crowsum1(x, f, t)
}
crowsum1 = cfunction(c(x_in="numeric", f_in="integer", t_in = "integer"), "
SEXP res_out;
double *x = REAL(x_in), *res;
int len = Rf_length(x_in), *f = INTEGER(f_in);
res_out = PROTECT(Rf_allocVector(REALSXP, Rf_length(t_in)));
res = REAL(res_out);
memset(res, 0, Rf_length(t_in) * sizeof(double));
for (int i = 0; i < len; ++i)
res[f[i] - 1] += x[i];
UNPROTECT(1);
return res_out;
")
与
> system.time(r1.1 <- rowsum1.1(x, f))
user system elapsed
1.276 0.092 1.373
要实际返回与rowsum
相同的结果,需要将其整形为具有适当暗淡名称的矩阵
rowsum1 <- function(x, f) {
t <- tabulate(f)
r <- crowsum1(x, f, t)
keep <- which(t != 0)
matrix(r[keep], ncol=1, dimnames=list(keep, NULL))
}
> system.time(r1 <- rowsum1(x, f))
user system elapsed
9.312 0.300 9.641
因此,对于所有这些工作,我们只快2倍(并且更不常见 - x必须是数字,f必须是整数;没有NA值)。是的,效率低下,例如,分配没有计数的空间级别(尽管这避免了对名称的字符向量的昂贵强制)。
答案 1 :(得分:4)
为了补充Martin的代码,这里有一些基于Rcpp
的版本。
int increment_maybe(int value, double vec_i){
return vec_i == 0 ? value : ( value +1 ) ;
}
// [[Rcpp::export]]
NumericVector cpprowsum2(NumericVector x, IntegerVector f){
std::vector<double> vec(10) ;
vec.reserve(1000);
int n=x.size();
for( int i=0; i<n; i++){
int index=f[i];
while( index >= vec.size() ){
vec.resize( vec.size() * 2 ) ;
}
vec[ index ] += x[i] ;
}
// count the number of non zeros
int s = std::accumulate( vec.begin(), vec.end(), 0, increment_maybe) ;
NumericVector result(s) ;
CharacterVector names(s) ;
std::vector<double>::iterator it = vec.begin() ;
for( int i=0, j=0 ; j<s; j++ ,++it, ++i ){
// move until the next non zero value
while( ! *it ){ i++ ; ++it ;}
result[j] = *it ;
names[j] = i ;
}
result.attr( "dim" ) = IntegerVector::create(s, 1) ;
result.attr( "dimnames" ) = List::create(names, R_NilValue) ;
return result ;
}
C ++代码处理所有内容,包括格式化为rowsum
给出的矩阵格式,并显示(稍微)更好的性能(至少在示例中)。
# from Martin's answer
> system.time(r1 <- rowsum1(x, f))
user system elapsed
0.014 0.001 0.015
> system.time(r3 <- cpprowsum2(x, f))
user system elapsed
0.011 0.001 0.013
> identical(r1, r3)
[1] TRUE
答案 2 :(得分:1)
这是我尝试使用Rcpp
(第一次使用软件包,所以请指出我的低效率):
library(inline)
library(Rcpp)
rowsum_helper = cxxfunction(signature(x = "numeric", y = "integer"), '
NumericVector var(x);
IntegerVector factor(y);
std::vector<double> sum(*std::max_element(factor.begin(), factor.end()) + 1,
std::numeric_limits<double>::quiet_NaN());
for (int i = 0, size = var.size(); i < size; ++i) {
if (sum[factor[i]] != sum[factor[i]]) sum[factor[i]] = var[i];
else sum[factor[i]] += var[i];
}
return NumericVector(sum.begin(), sum.end());
', plugin = "Rcpp")
rowsum_fast = function(x, y) {
res = rowsum_helper(x, y)
elements = which(!is.nan(res))
list(elements - 1, res[elements])
}
对于Martin的示例数据来说速度相当快,但只有当因子由非负整数组成并且会消耗因子向量中最大整数量级的内存时才会起作用(上面的一个明显改进是减去min)从max到减少内存使用 - 可以在R函数或C ++函数中完成。
n = 1e7; x = runif(n); f = sample(n/2, n, T)
system.time(rowsum(x,f))
# user system elapsed
# 14.241 0.170 14.412
system.time({tabulate(f); sum(x)})
# user system elapsed
# 0.216 0.027 0.252
system.time(rowsum_fast(x,f))
# user system elapsed
# 0.313 0.045 0.358
另请注意,R代码中出现了很多减速(与tabulate
相比),因此如果将其移至C ++,您应该会看到更多改进:
system.time(rowsum_helper(x,f))
# user system elapsed
# 0.210 0.018 0.228
这是一个可以处理几乎所有y
的概括,但会慢一点(我实际上更喜欢在Rcpp中这样做,但不知道如何处理任意R类型):< / p>
rowsum_fast = function(x, y) {
if (is.numeric(y)) {
y.min = min(y)
y = y - y.min
res = rowsum_helper(x, y)
} else {
y = as.factor(y)
res = rowsum_helper(x, as.numeric(y))
}
elements = which(!is.nan(res))
if (is.factor(y)) {
list(levels(y)[elements-1], res[elements])
} else {
list(elements - 1 + y.min, res[elements])
}
}
答案 3 :(得分:1)
在@Ben已删除的评论和“回答”中,结果是f
已订购并且正在增加。
n = 1e7; x = runif(n);
f <- cumsum(c(1L, sample(c(TRUE, FALSE), n - 1, TRUE)))
所以
rowsum3 <- function(x, f)
{
y <- cumsum(x)
end <- c(f[-length(f)] != f[-1], TRUE)
diff(c(0, y[end]))
}
是一种常见的R解决方案(如果不太关注精度),
crowsum3 <- cfunction(c(x_in="numeric", f_in="integer"), "
int j = 0, *f = INTEGER(f_in), len = Rf_length(f_in),
len_out = len == 0 ? 0 : f[len - 1];
SEXP res = Rf_allocVector(REALSXP, len_out);
double *x = REAL(x_in), *r = REAL(res);
memset(r, 0, len_out * sizeof(double));
for (int i = 0; i < len; ++i) {
if (i != 0 && f[i] != f[i-1]) ++j;
r[j] += x[i];
}
return res;
")
可能是C解决方案。这些有时间
> system.time(r3 <- rowsum3(x, f))
user system elapsed
1.116 0.120 1.238
> system.time(c3 <- crowsum3(x, f))
user system elapsed
0.080 0.000 0.081
并且R实现中的精度损失是显而易见的
> all.equal(r3, c3)
[1] TRUE
> identical(r3, c3)
[1] FALSE
rowsum_helper
已
> system.time(r2 <- rowsum_helper(x, f))
user system elapsed
0.464 0.004 0.470
但也假定基于0的索引
> head(rowsum_helper(x, f))
[1] NaN 0.9166577 0.4380485 0.7777094 2.0866507 0.7300764
> head(crowsum3(x, f))
[1] 0.9166577 0.4380485 0.7777094 2.0866507 0.7300764 0.7195091