Generating random numbers in R

2 posts / 0 new
Last post
statly
Offline
Joined: 10/10/2011
Generating random numbers in R

How do I select a random integer in R? I'm trying to generate a random integer between (and including) 50 and 60, but the runif() function returns decimal values. I could round the numbers, but that would mess up the distribution. What is the best way to select a random integer in R?

bryan
Offline
Joined: 01/15/2009

You can use the sample() function to do what you're trying to do. E.g.:

sample(50:60, size = 1)

You can also draw draw a larger set of numbers with or without replacement if you want:

sample(50:60, size = 3, replace = T)

One related trick - you can chose numbers at specific intervals by adding the seq() function:

sample(seq(50, 60, by = .5), size = 3, replace = T)

Login or register to post comments