-
Notifications
You must be signed in to change notification settings - Fork 30
/
030_basic_usage.Rmd
executable file
·81 lines (51 loc) · 1.92 KB
/
030_basic_usage.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# Basic usage
You can use your Rcpp function in 3 steps.
1. Writing Rcpp source code
2. Compiling the code
3. Executing the function
## Writing your Rcpp code
The below code defines a function `rcpp_sum()` that calculates the sum of a vector. Save this content as a file named "sum.cpp".
**sum.cpp**
```c++
//sum.cpp
#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);
}
```
### Format for defining a function in Rcpp.
The following code shows the basic format for defining a Rcpp function.
```cpp
#include<Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
RETURN_TYPE FUNCTION_NAME(ARGUMENT_TYPE ARGUMENT){
//do something
return RETURN_VALUE;
}
```
* `#include<Rcpp.h>` : This sentence enables you to use classes and functions defined by the Rcpp package.
* `// [[Rcpp::export]]`:The function defined just below this sentence will be accessible from R. You need to attach this sentence to every function you want to use from R.
* `using namespace Rcpp;` : This sentence is optional. But if you did not write this sentence, you have to add the prefix `Rcpp::` to specify classes and functions defined by Rcpp. (For example, `Rcpp::NumericVector`)
* `RETURN_TYPE FUNCTION_NAME(ARGUMENT_TYPE ARGUMENT){}`:You need to specify data types of functions and arguments.
* `return RETURN_VALUE;`:`return` statement is mandatory if your function would return a value. However, if your function do not return a value (i.e. `RETURN_TYPE` is `void`), the return statement can be omitted.
## Compiling the code
The function `Rcpp::sourceCpp()` will compile your source code and load the defined function into R.
```R
library(Rcpp)
sourceCpp('sum.cpp')
```
## Executing the function
You can use your Rcpp functions as usual R functions.
```r
> rcpp_sum(1:10)
[1] 55
> sum(1:10)
[1] 55
```