padrino
padrino

Reputation: 299

Variable number of entries to a single input argument

I am trying to write a function that can call varying distribution functions, depending on what the user gives as an Input. The following example is not from the code I am working on right now, but a simple, reproducible one:

fun <- function(dist, params){
  rdist <- get(paste("r", dist, sep=""), mode="function")
  return(rdist(n = 1, params))
}

But when I run the function using the following syntax, an obviously unwanted result appears:

> fun("norm", c(mean=1, sd=0))
[1] 1.713108

What does work is:

fun2 <- function(dist, params){
  rdist <- get(paste("r", dist, sep=""), mode="function")
  return(rdist(n = 1, params[1], params[2]))
}
> fun2("norm", c(mean=1, sd=0))
[1] 1

Is there a simple way to get the code in the former example to run like the latter?

Upvotes: 0

Views: 50

Answers (1)

agstudy
agstudy

Reputation: 121568

You are looking for :

do.call("rnorm", list(n=1,mean=1, sd=0))

you can wrap this in a function :

fun_dist <- function(dist="norm",...){
  rdist <- paste("r", dist, sep="")
  do.call(rdist, list(n=1,...))
}

Then you call it :

 fun_dist(mean=1, sd=0)
[1] 1

fun_dist('norm',mean=1, sd=0)
[1] 1

EDIT

The Op is looking for a solution where it give the parameters grouped in a single argument params.

fun_dist <- function(dist="norm",params){
  rdist <- paste("r", dist, sep="")
  do.call(rdist, as.list(c(n=1,params)))
}

fun_dist('norm',c(mean=1, sd=0))

Upvotes: 2

Related Questions