Reputation: 31741
I have a dataframe:
priors <- data.frame(dist = c('lnorm', 'beta', 'gamma'),
a = c(0.5, 1, 10),
b = c(0.4, 25, 4),
n = c(100, 100, 100)
)
and I would like to take n samples from the distribution with parameters a and b.
I have written this function:
pr.samp <- function(n,dist,a,b) {eval (parse (
text =
paste("r",dist,"(",n,",",a,",",b,")",sep = "")
))}
I would like to know:
Thanks in advance!
Upvotes: 1
Views: 429
Reputation: 108523
see ?do.call
pr.samp <- function(n,dist,a,b) {
do.call(paste('r',dist,sep=""),list(n,a,b))
}
Using an apply is difficult, as you have mixed character and numeric vectors in your dataframe. using apply on the rows will give you character vectors, which will cause errors. Converting to a matrix will give a character matrix. I'd do something like :
sapply(1:nrow(priors),function(x){
pr.samp(priors$n[x],priors$dist[x],priors$a[x],priors$b[x])})
Alternatively, the solution of Joshua is cleaner :
sapply(1:nrow(priors), function(x) do.call(pr.samp,as.list(priors[x,])))
Upvotes: 2