The Art of R Programming

(WallPaper) #1
To work in UDP, you need C/C++, which requires an interface to R for those
languages.
R actually offers two C/C++ interfaces via the functions.C()and
.Call(). The latter is more versatile but requires some knowledge of R’s
internal structures, so we’ll stick with.C()here.

15.1.1 Some R-to-C/C++ Preliminaries..................................


In C, two-dimensional arrays are stored in row-major order, in contrast to R’s
column-major order. For instance, if you have a 3-by-4 array, the element in
the second row and second column is element number 5 of the array when
viewed linearly, since there are three elements in the first column and this
is the second element in the second column. Also keep in mind that C sub-
scripts begin at 0, rather than at 1, as with R.
All the arguments passed from R to C are received by C as pointers.
Note that the C function itself must returnvoid. Values that you would
ordinarily return must be communicated through the function’s argu-
ments, such asresultin the following example.

15.1.2 Example: Extracting Subdiagonals from a Square Matrix...........


Here, we will write C code to extract subdiagonals from a square matrix.
(Thanks to my former graduate assistant, Min-Yu Huang, who wrote an ear-
lier version of this function.) Here’s the code for the filesd.c:

#include <R.h> // required

// arguments:
// m: a square matrix
// n: number of rows/columns of m
// k: the subdiagonal index--0 for main diagonal, 1 for first
// subdiagonal, 2 for the second, etc.
// result: space for the requested subdiagonal, returned here

void subdiag(double*m, int*n, int*k, double*result)
{
int nval =*n, kval =*k;
int stride = nval + 1;
for(inti=0,j=kval; i < nval-kval; ++i, j+= stride)
result[i] = m[j];
}

The variablestridealludes to a concept from the parallel-processing
community. Say we have a matrix in 1,000 columns and our C code is loop-
ing through all the elements in a given column, from top to bottom. Again,
since C uses row-major order, consecutive elements in the column are 1,000
elements apart from each other if the matrix is viewed as one long vector.

324 Chapter 15

Free download pdf