Last active
November 29, 2016 10:35
-
-
Save helmingstay/17d5d9f241c4170a29d1681db0111065 to your computer and use it in GitHub Desktop.
Example of R Reference Classes + Rcpp Attributes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <Rcpp.h> | |
using Rcpp::NumericVector; | |
// [[Rcpp::export]] | |
void convolveCpp(const NumericVector a, const NumericVector b, NumericVector xab) { | |
int na = a.size(), nb = b.size(); | |
if ( (na + nb-1) != xab.size() ) { | |
Rcpp::Rcout << "ab.size: " << na+nb << ", xab.size: " << xab.size() << std::endl; | |
Rcpp::stop("Dimension mismatch in convolveCpp"); | |
}; | |
// zero-out | |
xab.fill(0); | |
// convolve | |
for (int i = 0; i < na; i++) { | |
for (int j = 0; j < nb; j++) { | |
xab[i + j] += a[i] * b[j]; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(Rcpp) | |
sourceCpp('convolve.cpp') | |
Convolver <- setRefClass("Convolver", | |
fields = list( | |
data = "numeric", | |
answer = "numeric" | |
), | |
methods = list( | |
convolve = function(x) { | |
dim_new <- length(x)+length(data)-1 | |
## only re-alloc if necessary | |
if (length(answer) != dim_new) { | |
cat('## Realloc answer\n') | |
answer <<- numeric(dim_new) | |
} | |
convolveCpp(data, x, answer) | |
cat(c('Answer: ', round(answer,3), '\n')) | |
} | |
) | |
) | |
kernel1 <- c(1,3,1)/5 | |
kernel2 <- c(2,1,2)/5 | |
dat <- c(1:5, 0, 5:1) | |
the_test <- Convolver$new(data=dat/sum(dat)) | |
the_test$convolve(kernel1) | |
the_test$convolve(kernel2) |
source("Convolver.R")
(not ".cpp")?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In R, run with:
source("Convolver.cpp")