[R] Compute in C a loop with the lm() function and back to R
Javier López de Lacalle Beltrán de Heredia
javlacalle at yahoo.es
Mon Jun 19 18:59:17 CEST 2006
I want to do the computations from a loop by means of
a C routine that will be called from R. The lm()
function is entailed in that loop.
As a guidance, I have taken the following example from
http://www.math.mcgill.ca/steele/ (As far as my
question is concerned, I get similar information from
"writing R extensions" and the book "Econometrics in
R" by G.V Farnsworth):
Let convolve.rfun an R function
convolve.rfun <- function(a,b)
{
ab <- rep(0, length(a)+length(b)-1)
for(i in seq(along=a)){
for(j in seq(along=b))
ab[i+j-1] <- ab[i+j-1] + a[i]*b[j]
}
ab
}
then the following C code do the computations of
convolve.rfun,
void convolve(double *a, int *na, double *b, int *nb,
double *ab)
{
int i, j, nab = *na + *nb - 1;
for(i = 0; i < nab; i = i+1){
ab[i] = 0.0;
}
for(i = 0; i < *na; i = i + 1){
for(j = 0; j < *nb; j = j + 1){
ab[i + j] = ab[i+j] + a[i] * b[j];
}
}
}
which after being compiled (R CMD SHLIB convolve.c)
can be called from R:
dyn.load("convolve.so")
conv <- function(a, b){
.C("convolve", as.double(a), as.integer(length(a)),
as.double(b),
as.integer(length(b)),
ab=double(length(a)+length(b)-1))$ab
}
My question is: How should I write the corresponding C
code if the lm() R-function is entailed in the
computations of the loop in convolve.rfun() . How
could I get the OLS estimates in C?. Is there any
routine that I should include in the header of the C
file? Where to find it?
Thank you.
More information about the R-help
mailing list