How to handle list in R to Rcpp

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).

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)

Answers


A couple of small errors in here:

  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.

This version works:

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>  

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

Need Your Help

Setting HTML element width using ng-style and percentage value in AngularJS

javascript css json angularjs data-binding

I have a JSON response object which contains a percentage value. For example:

How to show a GUI message box from a bash script in linux?

linux bash scripting ubuntu gtk

I'm writing a few little bash scripts under Ubuntu linux. I want to be able to run them from the GUI without needing a terminal window to enter any input or view any output.