如何处理R到Rcpp中的列表 [英] How to handle list in R to Rcpp

查看:95
本文介绍了如何处理R到Rcpp中的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在R中有一个列表x <-list(c(1,2,3),c(4,5),c(5,5),c(6)).我想将列表输入Rcpp并将其作为平均向量c(2,4.5,5,6)返回.

I have a list in R that x<-list(c(1,2,3), c(4,5), c(5,5), c(6)). I want to input the list to Rcpp and return them as an average vector, c(2, 4.5, 5, 6).

我不确定如何在Rcpp中处理列表.我收到一条错误消息,有人可以检查我的代码吗?

I am not sure how to handle the list in Rcpp. I got an error message, so could someone check my code?

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. 两个语法错误:y需要Rcpp::NumericVector,并且在最后一个循环中缺少分号.
  2. 对C ++的一个误解:您需要类似std::vector<double> res(n);的东西,因为n在编译时是未知的.
  3. 在实例化列表中的向量时,您过于积极/乐观,我在两个语句中做到了这一点.
  1. Two syntax errors: you need Rcpp::NumericVector for y, and you lack a semicolon in the last loop.
  2. One misunderstanding of C++: you need something like std::vector<double> res(n); as n is not known at compile time.
  3. You were too aggressive / optimistic in instantiating your vectors from the list, I did this in two statements.

此版本有效:

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>  

这是一个更加惯用的版本:

Here is a version that is a little more idiomatic:

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

这篇关于如何处理R到Rcpp中的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆