Skip to content

Instantly share code, notes, and snippets.

@mikelove
Created July 30, 2014 18:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikelove/a78c8d3ccc0f2b41bd2a to your computer and use it in GitHub Desktop.
Save mikelove/a78c8d3ccc0f2b41bd2a to your computer and use it in GitHub Desktop.
Rcpp demo for BioC2014
# Rcpp demo
# Mike Love
# BioC2014
# 30 Jul 2014
# Go here for all the info:
# http://dirk.eddelbuettel.com/code/rcpp.html
# examples: go down to the 'Other documentation' vignettes
library(Rcpp)
library(inline)
f1 <- cxxfunction(
signature(xx = "integer", yy = "numeric" ),
'int x = as<int>(xx);
double y = as<double>(yy);
double z = x * y;
return wrap(z);',
plugin = "Rcpp" )
f1(10, 4.4)
############################################
# use Rcpp numeric vectors and sugar
# http://dirk.eddelbuettel.com/code/rcpp/Rcpp-sugar.pdf
f2 <- cxxfunction(
signature(xx = "numeric", yy = "numeric" ),
'Rcpp::NumericVector x(xx);
Rcpp::NumericVector y(yy);
Rcpp::NumericVector m = x * y;
Rcpp::NumericVector a = x + y;
return Rcpp::List::create(Rcpp::Named("multiply") = m,
Rcpp::Named("add") = a);',
plugin = "Rcpp" )
f2(1:5, 6:10)
############################################
# Armadillo C++ linear algebra library
# for nice looking matrix multiplication
# http://cran.r-project.org/web/packages/RcppArmadillo/vignettes/RcppArmadillo-intro.pdf
# The library documention is here: http://arma.sourceforge.net/docs.html
# I'm not sure the status of converting back and forth between arma objects and Rcpp
library(RcppArmadillo)
f3 <- cxxfunction(
signature(xx = "numeric", yy = "numeric" ),
'arma::mat x = Rcpp::as<arma::mat>(xx);
arma::mat y = Rcpp::as<arma::mat>(yy);
arma::mat m = x * y;
arma::mat s = sqrt(x);
return Rcpp::List::create(Rcpp::Named("multiply") = m,
Rcpp::Named("sqrt") = s);',
plugin = "RcppArmadillo" )
(xx <- matrix(1:6,ncol=2))
(yy <- matrix(1:8,ncol=4))
dim(xx)
dim(yy)
f3(xx,yy)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment