Friday, January 6, 2012

New function to sample from normal (or other types of) distributions

I just wrote a new function to generate a set of random data for individual observations as if they were drawn from a set of univariate normal distributions with species specific means and variances specified in a vector of means & variances. This is to automate the data simulation process for the fitBayes (e.g., see here). I have not yet posted this only, but the function is as follows:

sampleFrom<-function(xbar=0,xvar=1,n=1,randn=NULL,type="norm"){
  if(length(xvar)==1&&length(xbar)!=length(xvar))
    xvar<-rep(xvar,length(xbar))
  if(!is.null(randn))
    for(i in 1:length(xbar))
      n[i]<-floor(runif(n=1,min=randn[1],max=(randn[2]+1)))
  x<-vector()
  for(i in 1:length(xbar)){
    y<-rnorm(n=n[i],mean=xbar[i],sd=sqrt(xvar[i]))
    names(y)<-rep(names(xbar)[i],length(y))
    x<-c(x,y)
  }
  return(x)
}


Seems to work for what I'm trying to do. Let me know if you see any bugs.

No comments:

Post a Comment

Note: due to the very large amount of spam, all comments are now automatically submitted for moderation.