Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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).

like image 391
Rebecca J. Stones Avatar asked Mar 23 '23 04:03

Rebecca J. Stones


1 Answers

Try using replicate

replicate(10, x())

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

like image 99
Jilber Urbina Avatar answered Mar 24 '23 18:03

Jilber Urbina