[Rcpp-devel] Named vectors

Dirk Eddelbuettel edd at debian.org
Thu Sep 9 18:09:56 CEST 2010

On 9 September 2010 at 08:52, Andrew Redd wrote:
| What is the appropriate way to use/convert named vectors in C++ with
| Rcpp.  Basically I have a named vector of parameters that pass into
| the function.  I cannot be certain of their order, so would like to
| extract them by name.  For those initialized in C++ a
| std:map<std::string, double> should work, but how do declare one from
| a SEXP pointer that is passed in?  For example:
| draw <- cxxfunction(signature(A="numeric",t="numeric", params="numeric"),body="
|     SEXP draw( SEXP A, SEXP t, SEXP params){
|       Rcpp::NumericVector Admissions(A);
| 			Rcpp::NumericVector T(t);
| 			std::map<std::string, double> Params(params);
| 			std::vector<double> draws;
| 			for(int i=0;i<params[\"n\"];i++){
| 				draws.pushback(rbinom(Admissions[T[i]+1,2], 1/(1+exp(-params[\"nu\"])))));
| 			}
| 			return wrap(draws);
|     }
| 	",plugin='Rcpp')
| This of course does not compile because of std::map<std::string,
| double> Params(params); is not valid.  But is shows more of less what
| I'm trying to do.

There were numerous other errors I fixed:

1)  Do not add a function header as inline does that for you.

2)  Do not add a final } either.

3)  Your Params can be passed to a list as I showed.

4)  I do not understand what Admissions[T[i]+1,2] could possible do for a
    NumericVector Admissions. Did you mean a matrix?  Changed to vector.

5)  rbinom is now defined in SVN (wait for 0.8.6 "soon"). I presume you meant
    the function from R itself returning a double so I changed that with
    explicit prefixes.
So this now builds for me:

> draw <- cxxfunction(signature(A="numeric",t="numeric", params="numeric"),body="
+       Rcpp::NumericVector Admissions(A);
+       Rcpp::NumericVector T(t);
+       Rcpp::List Params(params);
+       int len = Rcpp::as<int>(Params[\"n\"]);
+       Rcpp::NumericVector draws(len);
+       for(int i=0; i<len; i++){
+           draws[i] = ::Rf_rbinom(Admissions[T[i]], 1/(1+exp(-Rcpp::as<double>(Params[\"nu\"]))));
+       }
+       return draws;
+ ",plugin='Rcpp')

We don;t need the Rcpp:: prefixes but I like'em too.

More information about the Rcpp-devel mailing list