c – 如何处理R到Rcpp中的列表
发布时间:2020-12-16 05:39:31 所属栏目:百科 来源:网络整理
导读:我在R中有一个列表,其中x -list(c(1,2,3),c(4,5),c(5,c(6)).我想将列表输入到Rcpp,并将它们作为平均向量c(2,4.5,5,6)返回. 我不知道如何处理Rcpp中的列表.我收到一条错误消息,有人可以检查我的代码吗? library(inline)fx = cxxfunction(signature(x='List')
我在R中有一个列表,其中x <-list(c(1,2,3),c(4,5),c(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,c(6)) fx(x) 解决方法
这里有几个小错误:
>两个语法错误:您需要R的Rcpp :: NumericVector,并且在最后一个循环中缺少一个分号. 此版本的作品: 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,c(6)) R> fx(x) [1] 6 9 10 6 R> 编辑:这是一个更加惯用的一个版本: fx <- cxxfunction(signature(x='List'),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); ') (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |