Andee Kaplan
R
Package Development with Rcpp
R
for development
sudo apt-get install r-base-dev
R
Packages Rcpp
and RcppArmadillo
install.packages(c("Rcpp", "RcppArmadillo"))
devtools::has_devel()
cppFunction()
allows you to write C++ functions in R
.
library(Rcpp)
cppFunction(
'int add(int x, int y, int z) {
int sum = x + y + z;
return(sum);
}'
)
add
## function (x, y, z)
## .Primitive(".Call")(<pointer: 0x107bf45a0>, x, y, z)
add(1, 2, 3)
## [1] 6
Rcpp
typesint
, double
, String
, bool
IntegerVector
, NumericVector
, CharacterVector
, LogicalVector
IntegerMatrix
, NumericMatrix
, CharacterMatrix
, LogicalMatrix
List
, DataFrame
Still use []
for accessing elements in Rcpp
vectors, but ()
for accessing alements in Rcpp
matrices.
sourceCpp
Can use standalone C++ files with extension .cpp
and source them into R
using sourceCpp()
. If you do this, must include
#include <Rcpp.h>
using namespace Rcpp;
at the top of your C++ file and for each function that you want to use in R
, prefix it with
// [[Rcpp::export]]
Then, you can source your function using
sourceCpp("code/timesTwo.cpp")
timesTwo(1:10)
## [1] 2 4 6 8 10 12 14 16 18 20
After editing/creating your package,
devtools::document()
RcppArmadillo
Armadillo is a C++ linear algebra library aiming towards a good balance between speed and ease of use. We can use the R
package RcppArmadillo
to interface with this library.
LinkingTo: Rcpp, RcppArmadillo
.cpp
file:#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp; using namespace arma;