[R] calling R's optimization routines from C

Globe Trotter itsme_410 at yahoo.com
Wed Mar 29 03:35:37 CEST 2006


Hi,

I have read R's Writing Extensions manual and am still confused about how to
use some of the routines there when I call from C. Specifically, I am writing a
little test function which I will optimize using the nmmin function which
underlies R's optim() with Nelder-Mead. I guess I wonder what library/header
files I should be using. I was using R_ext/Applic.h and linking with libR but I
can not get it to work. (Btw, I am using RHEL4/FC4 Linux).

The function is very simple: all it does is calculate the sum of squared
differences from a parameter, so the minimizer will be the mean.

Actually, here is my code:

#include<stdio.h>
#include<stdlib.h>

#include <R_ext/Applic.h>

typedef struct {
        double *X;
        int n;
} MyData;

double myfunc(int m, double *par, void *ex)
{
        MyData *mydata = ex;
        double *X = mydata->X;
        int n = mydata->n;
        double mu = par[0];
        double sum = 0.0;
        int i;

        for (i=0; i<n; i++) {
          double t = X[i] - mu;
             sum += t*t;
        }
        return sum;
}

int main(void)
{
  int i,n=1, trace=1, maxit=100, fail, fncount;
  double *par, abstol=0.0001, intol=.0001, alpha=1, beta=.5, gamma=2, *xin, *x,

Fmin; 

  MyData ex;

  par=malloc(n*sizeof(double));
  xin=malloc(n*sizeof(double));
  x=malloc(n*sizeof(double));

  par[0]=5;
  xin[0]=5;

  ex.n=5;

  ex.X=malloc(ex.n*sizeof(double));

  for(i=0;i<ex.n;i++) ex.X[i]=i;

  nmmin(n,xin,x,&Fmin,myfunc,&fail,abstol,intol,&ex,alpha,
        beta,gamma,trace,&fncount,maxit);
  free(par);
  free(x);
  free(xin);
  free(ex.X);
  return 0;
}


I compile using the following:

gcc -o testex testex.c -std=c99 -Wall -pedantic -I/usr/lib/R/include
-L/usr/lib/R/lib -lm -lR

Which actually compiles without error, but I get Segmentation fault when I run
it.

Clearly, I am doing something wrong. Can someone please provide suggestions? 

Many thanks and best wishes,
Aaarem




More information about the R-help mailing list