Rebecca J. Stones
Rebecca J. Stones

Reputation: 212

How to sample from a user-defined function that generates random numbers

I have written a function x <- function() ... that generates random numbers according to a distribution I'd like to study.

> x()
[1] 0.8947771
> x()
[1] 0.4478619

I can generate a list of 10 random numbers using x via a for loop:

> s <- c()
> for(i in 1:10) s <- c(s,x())
> s
 [1] 0.6035317 0.4556456 0.6063270 0.4567958 0.5805186 0.7688124 0.6722493
 [8] 0.3908357 0.4513608 0.2747064

However, this seems clumsy. I would like to know: is there a better way to create such a list?

There are some succinct ways of generating lists numbers in R, such as (1:10)^2 (which generates squares) and runif(10,0,1) (which generates uniformly random numbers between 0 and 1), rnorm(10) (which generates normal-distributed numbers) but I can't seem to get it to work in my case: x(1:10) returns Error in x(1:10) : unused argument(s) (1:10).

Upvotes: 4

Views: 1340

Answers (1)

Jilber Urbina
Jilber Urbina

Reputation: 61214

Try using replicate

replicate(10, x())

Also note that you are in Circle 2, read R inferno

Upvotes: 7

Related Questions