The Art of R Programming

(WallPaper) #1
Here, we would say that we are traversing that long vector with a stride of
1,000—that is, accessing every thousandth element.

15.1.3 Compiling and Running Code....................................


You compile your code using R. For example, in a Linux terminal window,
we could compile our file like this:

% R CMD SHLIB sd.c
gcc -std=gnu99 -I/usr/share/R/include -fpic -g -O2 -c sd.c -o sd.o
gcc -std=gnu99 -shared -o sd.so sd.o -L/usr/lib/R/lib -lR

This would produce the dynamic shared library filesd.so.
Note that R has reported how it invoked GCC in the output of the exam-
ple. You can also run these commands by hand if you have special require-
ments, such as special libraries to be linked in. Also note that the locations
of theincludeandlibdirectories may be system-dependent.

NOTE GCC is easily downloadable for Linux systems. For Windows, it is included in
Cygwin, an open source package available fromhttp://www.cygwin.com/.


We can then load our library into R and call our C function like this:

> dyn.load("sd.so")
> m <- rbind(1:5, 6:10, 11:15, 16:20, 21:25)
>k<-2
> .C("subdiag", as.double(m), as.integer(dim(m)[1]), as.integer(k),
result=double(dim(m)[1]-k))
[[1]]
[1] 1 6 11 16 21 2 7 12 17 22 3 8 13 18 23 4 9 14 19 24 5 10 15 20 25

[[2]]
[1] 5

[[3]]
[1] 2

$result
[1] 11 17 23

For convenience here, we’ve given the nameresultto both the formal
argument (in the C code) and the actual argument (in the R code). Note
that we needed to allocate space forresultin our R code.
As you can see from the example, the return value takes on the form
of a list consisting of the arguments in the R call. In this case, the call had
four arguments (in addition to the function name), so the returned list
has four components. Typically, some of the arguments will be changed
during execution of the C code, as was the case here withresult.

Interfacing R to Other Languages 325
Free download pdf