[Rcpp-devel] Accessing T of RcppVector<T>

Dirk Eddelbuettel edd at debian.org
Fri Oct 29 00:56:11 CEST 2010


Hi Sebastian,

You are doing a few things in a rather awkward manner.  One thing is that you
still stick to what we call the 'classic' API; most of us think you probably
want the newer one.  Have another look at the Rcpp-introduction vignette in
Rcpp 0.8.7 (maybe via the CRAN website). Also some of your R assignments
were, well, wrong as you were a little generous with the <-. 

With that, here is a simple example using Rcpp and inline.

First, I (re-)define your helper function, making the argument const:

> ## define our helper function, this will be passed as an include segment to cxxfunction()
> inc <- 'void other(const double any) {
+            std::cout << "YAY it works, value is " << any << std::endl;
+         }
+        '
>

Next, the body of the function.  We get a double, once as a vector (which
will have length 1 of we pass a scalar as we do here -- recall that
everything is a vector in R) and once as a double.

> ## body of function: get scalar two different way, use it
> src <- 'Rcpp::NumericVector vec = Rcpp::NumericVector(x);  // as vector
+         double dbl = Rcpp::as<double>(x);                  // as double
+         other(vec(0));
+         other(dbl);
+         return Rcpp::wrap(0);
+        '
>

We then make this a function in R using cxxfunction from inline:

> library(inline)
> fun <- cxxfunction(signature(x="numeric"),
+                    body=src, inc=inc, plugin="Rcpp")
>

And use it:
> num <- 42.1337
> fun(num)
YAY it works, value is 42.1337
YAY it works, value is 42.1337
[1] 0
> fun(3.1415)
YAY it works, value is 3.1415
YAY it works, value is 3.1415
[1] 0
> 

For reference, the whole code is again below.

Hope this helps, Dirk



## define our helper function, this will be passed as an include segment to cxxfunction()
inc <- 'void other(const double any) {
           std::cout << "YAY it works, value is " << any << std::endl;
        }
       '

## body of function: get scalar two different way, use it
src <- 'Rcpp::NumericVector vec = Rcpp::NumericVector(x);  // as vector
        double dbl = Rcpp::as<double>(x);                  // as double
        other(vec(0));
        other(dbl);
        return Rcpp::wrap(0);
       '


library(inline)
fun <- cxxfunction(signature(x="numeric"),
                   body=src, inc=inc, plugin="Rcpp")


num <- 42.1337
fun(num)
fun(3.1415)


-- 
Dirk Eddelbuettel | edd at debian.org | http://dirk.eddelbuettel.com


More information about the Rcpp-devel mailing list