練習 Practice 〜RstudioでC++を覚える

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
NumericVector positives(NumericVector x) {
    return x[x > 0];
}

// [[Rcpp::export]]
List first_three(List x) {
    IntegerVector idx = IntegerVector::create(0, 1, 2);
    return x[idx];
}

// [[Rcpp::export]]
List with_names(List x, CharacterVector y) {
    return x[y];
}

// [[Rcpp::export]]
NumericVector in_range(NumericVector x, double low, double high) {
    return x[x > low & x < high];
}

// [[Rcpp::export]]
NumericVector no_na(NumericVector x) {
    return x[ !is_na(x) ];
}

bool is_character(SEXP x) {
    return TYPEOF(x) == STRSXP;
}

// [[Rcpp::export]]
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++
    • R function
x <- rnorm(1000)
fivenum(x) # min,max,quantiles(x,c(0.25,0.5,0.75))
    • "callfunction.cpp"
#include <Rcpp.h>

using namespace Rcpp;

// [[Rcpp::export]]
NumericVector callFunction(NumericVector x, Function f) {
    NumericVector res = f(x);
    return res;
}
    • 使う Use it
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