Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R from C -- Simplest Possible Helloworld

Tags:

What is the simplest possible C function for starting the R interpreter, passing in a small expression (eg, 2+2), and getting out the result? I'm trying to compile with MingW on Windows.

like image 600
jsight Avatar asked Mar 17 '10 15:03

jsight


People also ask

How do you call C from R?

The most basic method for calling C code from R is to use the . C() function described in the System and foreign language interfaces section of the Writing R Extensions manual. Other methods exist including the . Call() and .

Does R use C?

So in conclusion: while R itself is mostly written in C (with hefty chunks in R and Fortran), R packages are mostly written in R (with hefty chunks written in C/C++).


1 Answers

You want to call R from C?

Look at section 8.1 in the Writing R Extensions manual. You should also look into the "tests" directory (download the source package extract it and you'll have the tests directory). A similar question was previously asked on R-Help and here was the example:

#include <Rinternals.h>  #include <Rembedded.h>   SEXP hello() {    return mkString("Hello, world!\n");  }   int main(int argc, char **argv) {    SEXP x;    Rf_initEmbeddedR(argc, argv);    x = hello();    return x == NULL;             /* i.e. 0 on success */  }  

The simple example from the R manual is like so:

 #include <Rembedded.h>   int main(int ac, char **av)  {      /* do some setup */      Rf_initEmbeddedR(argc, argv);      /* do some more setup */       /* submit some code to R, which is done interactively via          run_Rmainloop();           A possible substitute for a pseudo-console is           R_ReplDLLinit();          while(R_ReplDLLdo1() > 0) {            add user actions here if desired          }       */      Rf_endEmbeddedR(0);      /* final tidying up after R is shutdown */      return 0;  } 

Incidentally, you might want to consider using Rinside instead: Dirk provides a nice "hello world" example on the project homepage.

In you're interested in calling C from R, here's my original answer:

This isn't exactly "hello world", but here are some good resources:

  • Jay Emerson recently gave a talk on R package development at the New York useR group, and he provided some very nice examples of using C from within R. Have a look at the paper from this discussion on his website, starting on page 9. All the related source code is here: http://www.stat.yale.edu/~jay/Rmeetup/MyToolkitWithC/.
  • The course taught at Harvard by Gopi Goswami in 2005: C-C++-R (in Statistics). This includes extensive examples and source code.
like image 79
Shane Avatar answered Sep 16 '22 19:09

Shane