【问题标题】:How to handle list in R to Rcpp如何处理 R 中的列表到 Rcpp
【发布时间】:2012-10-04 01:56:25
【问题描述】:

我在 R 中有一个列表 x

我不确定如何处理 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)

【问题讨论】:

    标签: c++ r list rcpp


    【解决方案1】:

    这里有几个小错误:

    1. 两个语法错误:y 需要 Rcpp::NumericVector,并且最后一个循环中缺少分号。
    2. 对 C++ 的一个误解:你需要像 std::vector&lt;double&gt; 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);
    ')
    

    【讨论】:

    • 我是否正确理解此解决方案仅适用于这一特定级别的嵌套列表?
    • @Matt:如果您需要另一层(或两层或三层或......),您必须添加它们。嵌套没有限制,就像 R 中没有一样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-22
    • 2020-03-01
    • 1970-01-01
    相关资源
    最近更新 更多