[Rd] getting a vector of unown size

Marcelo Kittlein kittlein at mdp.edu.ar
Fri Sep 4 23:35:46 CEST 2015


Hi all!

I have written some code in C for simulating the fate of population 
using a dll loaded in R. During this simulation the population may go 
extinct such that the length of its trajectory is unknown beforehand. I 
wonder there is a way to define the size of the result in C and make it 
known to R to get the vector appropriately.

I have defined the output size very much larger than necessary to hold 
the result and then shrink the vector to the size where meaningful 
values occur, but this waste much resources and time unnecessarily.

The C code


#include <stdlib.h>
#include <math.h>


double min(double a, double b)
{
if(a>b)
return b;
else
return a;
}

double unirand()
{
return (rand()+1.0)/(RAND_MAX+1.0);
}

void RndSBDdemography(double *b, double *d, double *a, double *c, double 
*No, double *tmax, double *tiempo, double *Nind)
{
double tb, td, n;
int bc=0;
tiempo[0]=1.0;
Nind[0] = *No;

// This loop generates output of variable and a priori unknown size

while (Nind[bc] >= 2 && tiempo[bc] <= *tmax)
{
bc = bc + 1;
tb = -(1 / (*b - *a * Nind[bc-1])) * log(unirand());
td = -(1 / (*d + *c * Nind[bc-1])) * log(unirand());

tiempo[bc]= tiempo[bc-1] + min(tb, td)/ Nind[bc-1];

if (tb < td) n=1.0 ; else n= -1.0;

Nind[bc] = Nind[bc-1] + n;

}

}


The definition of the function call in R


RndSBDdemography = function(b=b,d=d,a=a,c=c, No=No, tmax=tmax){
tiempo=numeric(100000);
Nind=numeric(100000);
out=.C("RndSBDdemography",
b=as.double(b),
d=as.double(d),
a=as.double(a),
c=as.double(c),
No=as.double(No),
tmax=as.double(tmax),
tiempo=as.double(tiempo),
Nind=as.double(Nind)
)

# trim the output to a size where meaningful values occur
indi=which(out$tiempo!=0)
return(data.frame(tiempo=out$tiempo[indi], Nind=out$Nind[indi]))
}

Hope someone can give a hint on this.

Best Regards

Marcelo Kittlein



More information about the R-devel mailing list