sampling without replacement in C for use in R code

c, r

Solution

Likely the shared object needs to be compiled with a command like

export PKG_CFLAGS=`gsl-config --cflags`
export PKG_LIBS=`gsl-config --libs`

and then

R CMD SHLIB gsl.c

or alternatively

PKG_CFLAGS=`gsl-config --cflags` PKG_LIBS=`gsl-config --libs` R CMD SHLIB gsl.c

This is telling the compiler where to look for headers, and the linker where to find libraries to link against. During compilation and linking the commands should contain the output of `gsl-config --cflags` and `gsl-config --libs`, along the lines of

gcc -std=gnu99 -I/home/mtmorgan/bin/R-devel/include -I/usr/local/include -I/usr/include -fpi -c gsl.c -o gsl.o

during compilatoin and

gcc -std=gnu99 -shared -L/usr/local/lib64 -o gsl.so gsl.o -L/usr/lib -lgsl -lgslcblas -lm -L/home/mtmorgan/bin/R-devel/lib -lR

during linking. A test of success is

R -e 'dyn.load("gsl.so")'

In a package one would have a file `src/Makevars` with

PKG_CFLAGS = `gsl-config --cflags`
PKG_LIBS = `gsl-config --libs`

and, for Windows where `gsl-config` might not be available but the user has managed to install gsl and set an environment variable `LIB_GSL`, a file `src/Makevars.win`

PKG_LIBS += -L$(LIB_GSL)$(R_ARCH)/lib -lgsl -lgslcblas -lm
PKG_CPPFLAGS += -I$(RHOME)/src/include -I$(LIB_GSL)$(R_ARCH)/include

Problem

I am trying to write a function in C that will be called by R. Within it I need to take a random sample without replacement from a vector. Is it possible with Rmath.h to use something like sample() in R? If not, does anyone know why I might be getting ``` Symbol not found: _gsl_rng_mt19937 ``` When I try to dyn.load() code that calls that includes (with the appropriate headers): ``` #include <gsl/gsl_randist.h> #include <gsl/gsl_rng.h> void update_infs (int *inds, int *inf_times, int *n, int *n_inf, int *locs, int *Rinds, double *logmean, double *logsd, double *alpha, double *wts, int *indices /* a vector 1:n */ ) { ... /* set up GSL RNG */ gsl_rng * rng = gsl_rng_alloc(gsl_rng_mt19937); /* end of GSL setup */ ... gsl_ran_choose(rng, tmp_inf_me, Rinds[i], indices, *n, sizeof (double)); ... } ```

Original source