[Rcpp-devel] How to put the code 2013-01-05-r-function-from-c++.cpp in the src/ directory of a package?

Dirk Eddelbuettel edd at debian.org
Sun May 26 01:31:02 CEST 2013


On 25 May 2013 at 18:05, Peng Yu wrote:
| > You. Are. Still. Doing. It. Wrong.
| 
| I know that I did was wrong. Otherwise it should have worked. What's
| the point of reiterating it and emphasizing it? Something more
| constructive is more helpful.

You still don't know what functions to call when.  Here are two files. Copy
and paste from between the dashed lines.

--file 1: pengyu.cpp ------------------------------------------------------

#include <Rcpp.h>

using namespace Rcpp;

// [[Rcpp::export]]
NumericVector callFunction(NumericVector x, Function f) {
    NumericVector res = f(x);
    return res;
}
-----------------------------------------------------------------------------

You will note that this is the _same code as in the Rcpp Gallery post_.

Use it together with file 2:

--file 1: pengyu.R ------------------------------------------------------
library(Rcpp)

set.seed(42)
x <- rnorm(1e5)
print(fivenum(x))

sourceCpp("pengyu.cpp")
print(callFunction(x, fivenum)

cat("Done\n")
-----------------------------------------------------------------------------

Use it as follows:

-----------------------------------------------------------------------------
edd at max:/tmp$ Rscript pengyu.R 
[1] -4.04327635 -0.68238450 -0.00206637  0.67332471  4.32809127
[1] -4.04327635 -0.68238450 -0.00206637  0.67332471  4.32809127
Done
edd at max:/tmp$ 
-----------------------------------------------------------------------------

You could have run this straight from the Rcpp Gallery as well. Here I use
the URL for the raw file, download to a given filename and then call
sourceCpp() on that file:

-----------------------------------------------------------------------------
edd at max:/tmp$ wget
https://github.com/jjallaire/rcpp-gallery/raw/gh-pages/src/2013-01-05-r-function-from-c%2B%2B.cpp -OgalleryPost.cpp -q
edd at max:/tmp$ Rscript -e 'library(Rcpp); sourceCpp("galleryPost.cpp")'

R> set.seed(42)

R> x <- rnorm(1e+05)

R> fivenum(x)
[1] -4.04327635 -0.68238450 -0.00206637  0.67332471  4.32809127

R> callFunction(x, fivenum)
[1] -4.04327635 -0.68238450 -0.00206637  0.67332471  4.32809127
edd at max:/tmp$ 
-----------------------------------------------------------------------------

I have not hidden any secrets from you. You just managed to completely
misunderstand a few things, and then decided that you should just
semi-randomly guess a few new commands.  

Dirk, really tired of this

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


More information about the Rcpp-devel mailing list