From dfaden at gmail.com  Wed Jan  2 09:16:07 2008
From: dfaden at gmail.com (David Faden)
Date: Wed, 2 Jan 2008 02:16:07 -0600
Subject: [Rd] setting the seed in standalone code using Rlib
Message-ID: <6730abff0801020016m41b73fb9o4e832b4785d98853@mail.gmail.com>

Hi,

Is the below -- setSeed -- an okay way to set the seed in standalone
applications making use of Rlib? It seems to work as expected. Is
there a better way to do it? (I'm also looking at do_setseed but am
unsure what to supply as op. findFun("set.seed", R_GlobalEnv)?) Thanks
much.

-- 
David Faden, dfaden at iastate.edu
AIM: pitulx
--

#include <assert.h>
#include <R.h>
#include <Rinternals.h>
#include <R_ext/Parse.h>
#include <Rmath.h>
#include <stdio.h>

void setSeed(unsigned int seed)
{
#ifndef MATHLIB_STANDALONE

  /**
   * Following the example in Writing R Extensions 5.10
   */

  char cmd[256];
  SEXP cmdSexp;
  SEXP cmdExp;
  ParseStatus status;

  sprintf(cmd, "set.seed(%u)", seed);

  PROTECT(cmdSexp = allocVector(STRSXP, 1));
  SET_STRING_ELT(cmdSexp, 0, mkChar(cmd));
  cmdExp = PROTECT(R_ParseVector(cmdSexp, -1, &status, R_NilValue));

  assert(status == PARSE_OK);

  eval(VECTOR_ELT(cmdExp, 0), R_GlobalEnv);

  UNPROTECT(2);

#else

  set_seed(seed, seed);

#endif

}

/* Test */

extern int Rf_initEmbeddedR(int argc, const char *argv[]);

int main(int numArgs, char** args)
{
  const char *argv[]= {"setseed", "--gui=none", "--silent"};
  const int argc = 3;

  Rf_initEmbeddedR(argc, argv);

  setSeed((unsigned int)42);
  printf("%f\n", rnorm(0.0, 1.0));
  return 0;
}



[Rd] setting the seed in standalone code using Rlib
David Faden