[英]How to handle list in R to Rcpp
我在R中有一个列表x <-list(c(1,2,3),c(4,5),c(5,5),c(6))。 我想将列表输入到Rcpp并将它们作为平均向量返回,c(2,4,5,5,6)。
我不知道如何处理Rcpp中的列表。 我收到了错误消息,有人可以查看我的代码吗?
library(inline)
fx = cxxfunction(signature(x='List'), body =
'
Rcpp::List xlist(x);
int n = xlist.size();
double res[n];
for(int i=0; i<n; i++) {
Rcpp NumericVector y(xlist[i]);
int m=y.size();
res[i]=0;
for(int j=0; j<m; j++){
res[i]=res[i]+y[j]
}
}
return(wrap(res));
'
, plugin='Rcpp')
x<-list(c(1,2,3), c(4,5), c(5,5), c(6))
fx(x)
这里有几个小错误:
y
需要Rcpp::NumericVector
,并且在最后一个循环中缺少分号。 std::vector<double> res(n);
因为在编译时不知道n
。 这个版本有效:
R> fx <- cxxfunction(signature(x='List'), plugin='Rcpp', body = '
+ Rcpp::List xlist(x);
+ int n = xlist.size();
+ std::vector<double> res(n);
+
+ for(int i=0; i<n; i++) {
+ SEXP ll = xlist[i];
+ Rcpp::NumericVector y(ll);
+ int m=y.size();
+ res[i]=0;
+ for(int j=0; j<m; j++){
+ res[i]=res[i]+y[j];
+ }
+ }
+
+ return(Rcpp::wrap(res));
+ ')
R> x<-list(c(1,2,3), c(4,5), c(5,5), c(6))
R> fx(x)
[1] 6 9 10 6
R>
编辑:这是一个更惯用的版本:
fx <- cxxfunction(signature(x='List'), plugin='Rcpp', body = '
Rcpp::List xlist(x);
int n = xlist.size();
Rcpp::NumericVector res(n);
for(int i=0; i<n; i++) {
SEXP ll = xlist[i];
Rcpp::NumericVector y(ll);
for(int j=0; j<y.size(); j++){
res[i] += y[j];
}
}
return(res);
')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.