如何处理R到Rcpp中的列表

use*_*124 12 c++ r list 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)
Run Code Online (Sandbox Code Playgroud)

Dir*_*tel 23

这里有几个小错误:

  1. 两个语法错误:你需要Rcpp::NumericVectory,你没有在最后的循环分号.
  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>  
Run Code Online (Sandbox Code Playgroud)

编辑:这是一个更惯用的版本:

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);
')
Run Code Online (Sandbox Code Playgroud)

  • @Matt:如果你需要另一个层(或两个或三个或......),你必须_add_他们.嵌套没有限制,就像R中没有一样. (3认同)