- Reference
Read the web page The R Manuals, and
the PDF document Writing R Extensions (Chapter 5) in The R Manuals
(my mirror here).
- C code
The C code "callR.c" will
generate 10 random variables from standard normal (mu = 0, sigma = 1) and compute theirs cumulative probability,
and sort these 10 random variables, and print all results.
```
#include
#include
void callR(){
int i;
double mu, sigma, PHI_X, *X;
mu = 0;
sigma = 1;
X = (double *) R_alloc(10, sizeof(double));
Rprintf("Before sort\n");
GetRNGstate();
for(i = 0; i < 10; i++){
X[i] = rnorm(mu, sigma);
PHI_X = pnorm(X[i], mu, sigma, 1, 0);
Rprintf("X: %f, PHI(X): %f\n", X[i], PHI_X);
}
PutRNGstate();
R_rsort(X, 10);
Rprintf("After sort\n");
for(i = 0; i < 10; i++){
PHI_X = pnorm(X[i], mu, sigma, 1, 0);
Rprintf("X: %f, PHI(X): %f\n", X[i], PHI_X);
}
}
```
- Compile
- Linux:
```
SHELL> gcc -shared -o callR.so callR.c -I/usr/lib/R/include/ -L/usr/lib/R/bin/ -lR
```
or
```
SHELL> R CMD SHLIB callR.c
```
The output will be a shared library "callR.so"
which is a dynamic loading file as the dll file in MS Windows.
- R script
Create a R script "callR.r" to load the library and
execute it.
```
dyn.load("callR.so")
set.seed(10)
out <- .C("callR")
dyn.unload("callR.so")
```
- Output
The output is as the following,
```
Before sort
X: 0.018746, PHI(X): 0.507478
X: -0.184253, PHI(X): 0.426908
X: -1.371331, PHI(X): 0.085136
X: -0.599168, PHI(X): 0.274531
X: 0.294545, PHI(X): 0.615829
X: 0.389794, PHI(X): 0.651656
X: -1.208076, PHI(X): 0.113509
X: -0.363676, PHI(X): 0.358050
X: -1.626673, PHI(X): 0.051903
X: -0.256478, PHI(X): 0.398791
After sort
X: -1.626673, PHI(X): 0.051903
X: -1.371331, PHI(X): 0.085136
X: -1.208076, PHI(X): 0.113509
X: -0.599168, PHI(X): 0.274531
X: -0.363676, PHI(X): 0.358050
X: -0.256478, PHI(X): 0.398791
X: -0.184253, PHI(X): 0.426908
X: 0.018746, PHI(X): 0.507478
X: 0.294545, PHI(X): 0.615829
X: 0.389794, PHI(X): 0.651656
```
- Question
Why not to use executable file? How to build a "callR.exe"?
See Standalone.
---