Rcpp

Rcpp4everyone

https://dirk.eddelbuettel.com/papers/useR2019_rcpp_tutorial.pdf

https://www.runoob.com/cplusplus/cpp-tutorial.html

17.1 数据结构

17.1.1 向量类

NumericVector IntegerVector CharacterVector LogicalVector

Show the code
library(Rcpp)
sourceCpp("function/sum_cpp.cpp")
#> 
#> > sum_cpp(c(1, 2, 3))
#> [1] 6

sum_cpp(mpg$displ)
#> [1] 812.4
sum(mpg$displ)
#> [1] 812.4

sourceCpp("function/mean_cpp.cpp")
#> 
#> > x = c(1, 2, 3, 4, 5)
#> 
#> > mean_cpp(x)
#> [1] 3
mean_cpp(mpg$displ)
#> [1] 3.471795

NumericMatrix IntegerMatrix CharacterMatrix LogicalMatrix

17.1.2 数据框类

DataFrame

17.1.3 列表类

List

Show the code
# 平均百分比误差
sourceCpp("function/mpe.cpp")
#> 
#> > model <- lm(mpg ~ wt, data = mtcars)
#> 
#> > mpe(model)
#> [1] -0.01541615
mod <- lm(mpg ~ wt, data = mtcars)
mpe(mod)
#> [1] -0.01541615

17.1.4 函数类

Show the code
cppFunction("RObject callWithOne(Function f) {
  return f(1);
}")

callWithOne(function(x) x + 1)
#> [1] 2
callWithOne(paste)
#> [1] "1"

17.1.5 属性

Show the code
cppFunction('NumericVector attribs() {
  NumericVector out = NumericVector::create(1, 2, 3);

  out.names() = CharacterVector::create("a", "b", "c");
  out.attr("my-attr") = "my-value";
  out.attr("class") = "my-class";

  return out;
}')


attribs()
#> a b c 
#> 1 2 3 
#> attr(,"my-attr")
#> [1] "my-value"
#> attr(,"class")
#> [1] "my-class"

17.2 Rcpp sugar