Title: | Examples using 'Rcpp' to Interface R and C++ |
---|---|
Description: | Examples for Seamless R and C++ integration The 'Rcpp' package contains a C++ library that facilitates the integration of R and C++ in various ways. This package provides some usage examples. Note that the documentation in this package currently does not cover all the features in the package. The site <https://gallery.rcpp.org> regroups a large number of examples for 'Rcpp'. |
Authors: | Dirk Eddelbuettel [aut, cre] , Romain Francois [aut] |
Maintainer: | Dirk Eddelbuettel <[email protected]> |
License: | GPL (>= 2) |
Version: | 0.1.9.3 |
Built: | 2024-12-12 06:13:08 UTC |
Source: | https://github.com/eddelbuettel/rcppexamples |
This package shows some simple examples for the use of Rcpp.
It can also serve as a working template to create packages that use Rcpp to interface C++ code or libraries.
The Rcpp package provides a number of C++ classes that ease access to C++ from R. This comprises both passing parameters to functions, as well as returning results back from C++ to R.
The RcppExamples package provides some simple examples for use of Rcpp. At this point the documentation is not complete in the sense of not covering all accessible classes. However, several basic use cases are illustrated,
Dominick Samperi wrote the initial versions of Rcpp (and RcppTemplate) during 2005 and 2006. Dirk Eddelbuettel made some additions, and became maintainer in 2008. Dirk Eddelbuettel and Romain Francois have been extending Rcpp since 2009.
The https://gallery.rcpp.org site regroups a number of examples.
These two functions are an illustration of how as.character
and
as.factor
may be reimplemented at the C++ level.
factor2char(iv) char2factor(sv)
factor2char(iv) char2factor(sv)
iv |
A Integer Vector corresponding to numeric representation of the factor This vector is also expected to have an attribute ‘levels’ with the factor levels |
sv |
A String Vector |
A Character Vector which at each position contains the level value of the corresponding index, or a Factor, depending on the function
f <- as.factor(c("red", "green", "blue", "red")) factor2char(f); f <- as.factor(c("red", "green", "blue", "red")) v <- factor2char(f); char2factor(v)
f <- as.factor(c("red", "green", "blue", "red")) factor2char(f); f <- as.factor(c("red", "green", "blue", "red")) v <- factor2char(f); char2factor(v)
A DataFrame
can be passed C++ and can be instantiated as a
corresponding C++ object using the Rcpp API.
This example shows (in the corresponding C++ code) how to access, modify and create a data frame.
Usage of Rcpp::DataFrame
is fully defined in
the respective header file.
The C++ source file corresponding to the this function does the following:
// we receive a 'DF' data.frame object // and access each column by name Rcpp::IntegerVector a = DF["a"]; Rcpp::CharacterVector b = DF["b"]; Rcpp::DateVector c = DF["c"]; // do something a[2] = 42; b[1] = "foo"; c[0] = c[0] + 7; // move up a week // create a new data frame Rcpp::DataFrame NDF = Rcpp::DataFrame::create(Rcpp::Named("a")=a, Rcpp::Named("b")=b, Rcpp::Named("c")=c); // and return old and new in list return(Rcpp::List::create(Rcpp::Named("origDataFrame")=DF, Rcpp::Named("newDataFrame")=NDF));
Dirk Eddelbuettel and Romain Francois
## Not run: RcppDataFrame() ## End(Not run)
## Not run: RcppDataFrame() ## End(Not run)
Rcpp has the classes Rcpp::Date
, Rcpp::Datetime
,
Rcpp::DateVector
and Rcpp::DatetimeVector
.
In the C++
code for the RcppDateExample.cpp
file:
// [[Rcpp::export]] List DateExample(DateVector & dv, DatetimeVector & dtv) { Function formatDate("format.Date"); Function formatDatetime("format.POSIXct"); Rprintf("\nIn C++, seeing the following date value\n"); for (int i=0; i<dv.size(); i++) { Rcout << as<std::string>(formatDate(wrap(dv[i]))) << std::endl; dv[i] = dv[i] + 7; // shift a week } Rprintf("\nIn C++, seeing the following datetime value\n"); for (int i=0; i<dtv.size(); i++) { Rcout << as<std::string>(formatDatetime(wrap(dtv[i]))) << std::endl; dtv[i] = dtv[i] + 0.250; // shift 250 millisec } // Build result set to be returned as a list to R. return List::create(Named("date", dv), Named("datetime", dtv)); }
Dominick Samperi wrote the initial versions of Rcpp (and RcppTemplate) during 2005 and 2006. Dirk Eddelbuettel made some additions, and became maintainer in 2008. Dirk Eddelbuettel and Romain Francois have been extending Rcpp since 2009.
Writing R Extensions, available at https://www.r-project.org.
# set up date and datetime vectors dvec <- Sys.Date() + -2:2 dtvec <- Sys.time() + (-2:2)*0.5 # call the underlying C++ function result <- RcppDateExample(dvec, dtvec) # inspect returned object result
# set up date and datetime vectors dvec <- Sys.Date() + -2:2 dtvec <- Sys.time() + (-2:2)*0.5 # call the underlying C++ function result <- RcppDateExample(dvec, dtvec) # inspect returned object result
List
is an Rcpp
class that can be used to manipulate R lists.
params |
A heterogeneous list specifying |
RcppListExample
returns a list containing:
method |
string input paramter |
tolerance |
double input paramter |
maxIter |
int input parameter |
startDate |
Date type with starting date |
params |
input parameter list (this is redundant because we returned the input parameters above) |
Dominick Samperi wrote the initial versions of Rcpp (and RcppTemplate) during 2005 and 2006. Dirk Eddelbuettel made some additions, and became maintainer in 2008. Dirk Eddelbuettel and Romain Francois have been extending Rcpp since 2009.
Writing R Extensions, available at https://www.r-project.org.
# set up some value params <- list(method='BFGS', tolerance=1.0e-5, maxIter=100, startDate=as.Date('2006-7-15')) # call the underlying C++ function result <- RcppListExample(params) # inspect returned object result
# set up some value params <- list(method='BFGS', tolerance=1.0e-5, maxIter=100, startDate=as.Date('2006-7-15')) # call the underlying C++ function result <- RcppListExample(params) # inspect returned object result
The NumericMatrix
class represents numeric matrices
The C++
code presented in the MatrixExample.cpp
file:
#include <Rcpp.h> #include <cmath> // suncc needs help to disambiguate between sqrt( float ) and sqrt(double) inline static double sqrt_double(double x) { return ::sqrt(x); } using namespace Rcpp; // [[Rcpp::export]] List MatrixExample(const NumericMatrix & orig) { NumericMatrix mat(orig.nrow(), orig.ncol()); // we could query size via // int n = mat.nrow(), k=mat.ncol(); // and loop over the elements, but using the STL is so much nicer // so we use a STL transform() algorithm on each element std::transform(orig.begin(), orig.end(), mat.begin(), sqrt_double ); return List::create(Named("result") = mat, Named("original") = orig); }
Dominick Samperi wrote the initial versions of Rcpp (and RcppTemplate) during 2005 and 2006. Dirk Eddelbuettel made some additions, and became maintainer in 2008. Dirk Eddelbuettel and Romain Francois have been extending Rcpp since 2009.
Writing R Extensions, available at https://www.r-project.org.
M <- matrix((1:16)^2, 4) RcppMatrixExample(M)
M <- matrix((1:16)^2, 4) RcppMatrixExample(M)
Example on how to use a NumericVector and manipulate it with the STL.
NumericVector orig ; // from R NumericVector vec(orig.size()); // create a target vector of the same size // we could query size via // int n = vec.size(); // and loop over the vector, but using the STL is so much nicer // so we use a STL transform() algorithm on each element std::transform(orig.begin(), orig.end(), vec.begin(), sqrt_double ); return List::create(Named("result") = vec, Named("original") = orig);
As shown in the example section, provided the seed is reset, the exact same draws can be obtained in R itself – which is important for reproducibility.
Dirk Eddelbuettel and Romain Francois
RcppNumericVectorExample(seq(1,9)^2)
RcppNumericVectorExample(seq(1,9)^2)
Rcpp sugar provides numerous p/q/d/r functions for numerous distributions.
This example shows (in the corresponding C++ code) how to draw from three different distributions and returns a data frame.
The various header file, and the Rcpp sugar vignette, provide full documentation for Rcpp sugar.
The C++ source file corresponding to the this function does the following:
int n; // length passed in from R NumericVector rn = rnorm(n); NumericVector rt = rt(n, 1.0); NumericVector rp = rpois(n, 1.0); // create a new data frame to return drawns return DataFrame::create(Named("rnorm") = rn, Named("rt") = rt, Named("rpois") = rp);
As shown in the example section, provided the seed is reset, the exact same draws can be obtained in R itself – which is important for reproducibility.
Dirk Eddelbuettel and Romain Francois
set.seed(42) X <- RcppRNGsExample(10L) set.seed(42) Y <- data.frame(rnorm=rnorm(10),rt=rt(10,1),rpois=rpois(10,1)) all.equal(X,Y)
set.seed(42) X <- RcppRNGsExample(10L) set.seed(42) Y <- data.frame(rnorm=rnorm(10),rt=rt(10,1),rpois=rpois(10,1)) all.equal(X,Y)
The StringVector
(aka CharacterVector
)
class represents character vectors.
The C++
code presented in the StringVectorExample.cpp
file:
#include <Rcpp.h> using namespace Rcpp ; // [[Rcpp::export]] List StringVectorExample(const StringVector & orig) { StringVector vec(orig.size()); std::transform(orig.begin(), orig.end(), vec.begin(), make_string_transformer(tolower)); return List::create(Named("result") = vec, Named("original") = orig); }
Dominick Samperi wrote the initial versions of Rcpp (and RcppTemplate) during 2005 and 2006. Dirk Eddelbuettel made some additions, and became maintainer in 2008. Dirk Eddelbuettel and Romain Francois have been extending Rcpp since 2009.
Writing R Extensions, available at https://www.r-project.org.
RcppStringVectorExample(c("Tick", "Tack", "Tock"))
RcppStringVectorExample(c("Tick", "Tack", "Tock"))