如何处理R到RCPP中的列表

How to handle list in R to Rcpp

本文关键字:RCPP 列表 何处理 处理      更新时间:2023-10-16

我在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)

这里有几个小错误:

  1. 两个语法错误:您需要Rcpp::NumericVector才能y,并且在最后一个循环中缺少分号。
  2. 对C++的一个误解是:你需要类似std::vector<double> res(n);的东西,因为n在编译时是未知的。
  3. 您在从列表中实例化您的向量时过于激进/乐观,我在两个语句中做到了这一点。

此版本适用于:

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);
')