FakeAnalyst56
FakeAnalyst56

Reputation: 139

How to make probability distribution an argument of a function in R?

I have a function f in R which involves drawing many samples of the form

sample <- rnorm(k,0,1) 

where k is some integer. I would like to make as an argument of this function f the type of distribution, so I can quickly generate samples of the form

sample <- runif(k,0,1)

or other probability distributions for instance. In other words, I want to be able to write f(k,uniform) and generate the second type of sampling, and f(k,normal) for the first.

Is this possible? I'd like to avoid having to repeatedly modify the code within my functions each time I change distributions.

Upvotes: 1

Views: 364

Answers (2)

bschneidr
bschneidr

Reputation: 6278

Here's a promising, in-development implementation of what you're looking for. The distributions package is available on Github and on CRAN.

Here's an example usage:

library(distributions)

X <- Bernoulli(0.1)

random(X, 10)
#>  [1] 0 0 0 0 0 0 0 0 1 0
pdf(X, 1)
#> [1] 0.1

cdf(X, 0)
#> [1] 0.9
quantile(X, 0.5)
#> [1] 0

Upvotes: 3

John Coleman
John Coleman

Reputation: 51998

Don't know how useful this is, but:

f <- function(k,g){g(k)}

Used like f(100,runif) or f(100,rnorm)

As a variation:

f <- function(k,g,...){g(k,...)}

which would also allow things like f(100,rnorm,10,2)

Upvotes: 3

Related Questions