7  Rcpp

Rcpp

Rcpp4everyone

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

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

7.1 返回单个值,参数的数据结构

7.1.1 向量类

const

NumericVector IntegerVector CharacterVector LogicalVector

Show the code
library(Rcpp)
sourceCpp("function/sum_cpp.cpp")
#> 
#> > sum_cpp(1:5)
#> [1] 15

sum_cpp(mtcars$disp)
#> [1] 7383.1
sum(mtcars$disp)
#> [1] 7383.1

sourceCpp("function/mean_cpp.cpp")
#> 
#> > mean_cpp(1:5)
#> [1] 3
mean_cpp(mtcars$disp)
#> [1] 230.7219

NumericMatrix IntegerMatrix CharacterMatrix LogicalMatrix

7.1.2 数据框

DataFrame

7.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

7.1.4 函数类

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

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

7.2 属性

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"

7.3 Rcpp sugar