You are here: Vanderbilt Biostatistics Wiki>Main Web>WritingRExtensions (revision 1)EditAttach

Writing Extensions in R

You can write extensions for R in FORTRAN or C to help speed things up. This is useful if your R code involves lots of loops or other things that can be better handled in an external language. Most of this information and more can be found in the Writing R Extensions manual.

Hello world!

Let's start with the simplest extension in C: the obligatory "Hello world!" extension.

In your C source code, the first thing you have to do is include a few header files from the R library (in addition to any other includes you might need):

#include "R.h"
#include "Rdefines.h"
#include "R_ext/Rdynload.h"

The rest of the source includes any functions you want to call from R. In this example, we have a hello_world() function.

void hello_world() {
    printf("Hello world!\n");

Easy enough. If you want to send arguments to any external functions (which you will probably want to do), you'll need to add some parameters with types specific to what you're expecting from the user. More on that with the next example.

Next you need to register this function with R and tell it how it should be called. You do this through the R_init_<lib> function, where lib is the name of the shared library you want to create (in this case, "hello_world"). Here's the code needed for our example:

R_CMethodDef cMethods[] =
    {"hello_world", (DL_FUNC)&hello_world, 0},
    {NULL,NULL, 0}

void R_init_hello_world(DllInfo *dll)

Now you're ready to compile!
Topic attachments
I Attachment Action Size Date Who Comment hello_world.c manage 0.3 K 06 Jan 2006 - 17:38 JeremyStephens hello world extension hello_you.c manage 0.4 K 06 Jan 2006 - 17:38 JeremyStephens hello you extension pretty_matrix.c manage 1.7 K 06 Jan 2006 - 17:39 JeremyStephens pretty matrix extension
Edit | Attach | Print version | History: r6 | r4 < r3 < r2 < r1 | Backlinks | View wiki text | Edit WikiText | More topic actions...
Topic revision: r1 - 06 Jan 2006, JeremyStephens

This site is powered by FoswikiCopyright © 2013-2022 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding Vanderbilt Biostatistics Wiki? Send feedback