2012-10-04 23 views
11

我在R中有一個列表,其中列出了c(1,2,3),c(4,5),c(5,5),c(6) )。我想輸入列表到Rcpp並將它們作爲平均向量c(2,4.5,5,6)返回。如何處理R中的列表到Rcpp

我不知道如何處理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) 

回答

21

在這裏有幾個小錯誤:

  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> 

編輯:這裏是一個版本,是一個小更地道:

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

謝謝你這麼多。 – user1690124

+0

我的榮幸,請隨時「接受」(點擊刻度線)和「向上投票」(點擊向上的三角形),就像在StackOverflow上常見的一樣。 –

+0

我是否正確理解此解決方案僅適用於此特定級別的嵌套列表? –