-
Notifications
You must be signed in to change notification settings - Fork 30
/
040_function.Rmd
executable file
·54 lines (40 loc) · 1.01 KB
/
040_function.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# Embedding Rcpp code in your R code
You can also write Rcpp code in your R code in 3 ways using `sourceCpp()` `cppFunction()` `evalCpp()` respectively.
## sourceCpp()
Save Rcpp code as string object in R and compile it with `sourceCpp()`.
``` R
src <-
"#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
double rcpp_sum(NumericVector v){
double sum = 0;
for(int i=0; i<v.length(); ++i){
sum += v[i];
}
return(sum);
}"
sourceCpp(code = src)
rcpp_sum(1:10)
```
## cppFunction()
The `cppFunction()` offers a handy way to create a single Rcpp function. You can omit `#include <Rcpp.h>` and `using namespase Rcpp;` when you use `cppFunction()`.
```r
src <-
"double rcpp_sum(NumericVector v){
double sum = 0;
for(int i=0; i<v.length(); ++i){
sum += v[i];
}
return(sum);
}
"
Rcpp::cppFunction(src)
rcpp_sum(1:10)
```
## evalCpp()
You can evaluate a single C++ statement by using `evalCpp()`.
```r
# Showing maximum value of double.
evalCpp('std::numeric_limits<double>::max()')
```