Download An introduction to R

Transcript
CHAPTER 6. EFFICIENT . . .
6.4. SOME COMPILED CODE . . .
REAL(ans)[0] = mys;
UNPROTECT(1);
return ans;
}
The lower bound a and the upperbound b are of type SEXP and are passed from R to the
C code, they are converted to double and passed to the qromb function. This function
returns the result in the double variable mys, which we transform to a variable of type
SEXP so that it can be passed to R.
The only modification to the existing C code qromb, is the addition of two input parameters fn and rho which will be needed when we want to evaluate the R function that
is given by fn. In fact, the function qromb calls polint and trapzd that will call the
function fn, so these functions also need to be given fn and rho.
Modifying the function func Normally, when you want to use the function qromb in
a stand alone C program then the function to integrate is programmed in the function
func. Now this function needs to be adjusted in such a way that it evaluates the function
fn that you have given from R.
double func(const double x, SEXP fn, SEXP rho)
{
SEXP R_fcall, fn_out, x_input;
PROTECT(R_fcall = lang2(fn, R_NilValue));
PROTECT(x_input = allocVector(REALSXP, 1));
PROTECT(fn_out = allocVector(VECSXP, 1));
REAL(x_input)[0] = x;
SETCADR(R_fcall, x_input);
fn_out = eval(R_fcall,rho);
UNPROTECT(3);
return REAL(fn_out)[0];
}
The same constructions are used as in the previous example. Evaluating the R functions
results in a variable of type SEXP, this is then converted to a double and returned by
func. When the dll is compiled we can link it to R and run the function.
mydll = "C:\\Test\\Release\\Integrate.dll"
dyn.load(mydll)
myf <- function(x)
{
101