如何处理R到RCPP中的列表
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)
这里有几个小错误:
- 两个语法错误:您需要
Rcpp::NumericVector
才能y
,并且在最后一个循环中缺少分号。 - 对C++的一个误解是:你需要类似
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);
')
相关文章:
- Pybind11:将元组列表从Python传递到C++
- 从链接列表c++中删除一个项目
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- C++如何通过用户输入删除列表元素
- 读取文件的最后一行并输入到链接列表时出错
- 复制列表初始化的隐式转换的等级是多少
- LNK2038、MSVS2017 MAGMA的原因列表
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 使用 Rcpp 加速替换迭代算法中的列表和向量元素是否合法?
- 我如何将矩阵列表从RCPP返回到R
- RCPP:将布尔值传递在列表中从R到C 函数的错误,该函数获取RCPP ::列表
- Rcpp:"运算符="矩阵和列表的不明确重载
- RCPP:处理包含列表的列表
- 如何处理R到RCPP中的列表
- Rcpp - 从矩阵/数据帧列表中提取行
- Rcpp犰狳中列表组件的矩阵乘法
- 如何在 RCPP 中访问列表
- Rcpp犰狳:对列表元素的"-="操作
- Rcpp地图/词典/列表
- Rcpp如何在R列表中直接更改值