[R] Use R function in C code

James Wettenhall wettenhall at wehi.edu.au
Thu Apr 15 08:14:28 CEST 2004


Hi,

On Fri Apr 2, xt_wang wrote:
> I want to use R function Matrix inverse in my c code, please 
> tell me how I can.
> If there is a sample which can tell me how it works. It will 
> be fantastic.

A good place to start learning how to interface R with C is the 
"Writing R Extensions" manual installed locally, or:
http://cran.r-project.org/doc/manuals/R-exts.pdf
http://rweb.stat.umn.edu/R/doc/manual/R-exts.html

See also the article "In Search of C/C++ & Fortran Routines" in: 
http://cran.r-project.org/doc/Rnews/Rnews_2001-3.pdf

I guess you'd have to decide whether you want to compile R as a 
shared library or not.  I've never done this.

But do you really want to call R from C to get a matrix inverse?  
Can't you just use a CLAPACK routine?
http://www.netlib.org/clapack/

I'm not sure which CLAPACK subroutine is best for your purposes, 
but I have in the past used dgels (double-precision gaussian 
elimination and least-squares) and found it to be good.

I assume you have asked the question: 
"Do I really need an inverse?"

If Ax = b,
x = inv(A) * b 
is computationally about twice as expensive as Gaussian 
Elimination.

In R, to get help on solving linear systems, try:
?solve

> A <- matrix(c(1,2,3,4),nrow=2)
> Ainv <- solve(A)
> A %*% Ainv
     [,1] [,2]
[1,]    1    0
[2,]    0    1

Hope this helps,
James




More information about the R-help mailing list