#include <Rcpp.h>
using namespace Rcpp;
NumericVector positives(NumericVector x) {
return x[x > 0];
}
List first_three(List x) {
IntegerVector idx = IntegerVector::create(0, 1, 2);
return x[idx];
}
List with_names(List x, CharacterVector y) {
return x[y];
}
NumericVector in_range(NumericVector x, double low, double high) {
return x[x > low & x < high];
}
NumericVector no_na(NumericVector x) {
return x[ !is_na(x) ];
}
bool is_character(SEXP x) {
return TYPEOF(x) == STRSXP;
}
List charvecs(List x) {
return x[ sapply(x, is_character) ];
}
- Rで読んで、実行する Read it into R and use it.
install.packages("microbenchmark")
library(microbenchmark)
sourceCpp("vectorsubsetting.cpp")
R_in_range <- function(x, low, high) {
return(x[x > low & x < high])
}
x <- rnorm(1E5)
identical( R_in_range(x, -1, 1), in_range(x, -1, 1) )
microbenchmark( times=5,
R_in_range(x, -1, 1),
in_range(x, -1, 1)
)
-
- うまく動いたら、何をしているか確認してみる。It runs ok? then read codes to understand how it works.
- C++内でRの関数を使ってみる Use a R function in C++
x <- rnorm(1000)
fivenum(x)
#include <Rcpp.h>
using namespace Rcpp;
NumericVector callFunction(NumericVector x, Function f) {
NumericVector res = f(x);
return res;
}
sourceCpp("callfunction.cpp")
callFunction(x,fivenum)
fivenum(x)
> sourceCpp("callfunction.cpp")
> callFunction(x,fivenum)
[1] -2.96348996 -0.70554582 -0.01415115 0.66923375 3.05126692
> fivenum(x)
[1] -2.96348996 -0.70554582 -0.01415115 0.66923375 3.05126692