简体   繁体   中英

how to generate random numbers with sequence in R

I need to generate random numbers between 20 and 50 with 5 increments. For example, the numbers must be 20, 25, 30, 25, 50, 45 etc. The difference between numbers should be 5.

I tried this:

x<-floor(runif(50,20,50))

this gives me any number between 20 and 50. Is there an easy way to do this in R?

I think Arun was referring to this:

set.seed(123)
sample(seq(from = 20, to = 50, by = 5), size = 50, replace = TRUE)
#  [1] 30 45 30 50 50 20 35 50 35 35 50 35 40 40 20 50 25 20 30 50 50 40 40 50 40
# [26] 40 35 40 30 25 50 50 40 45 20 35 45 25 30 25 20 30 30 30 25 20 25 35 25 50

Very similar to your original code, but dividing and multiplying by 5 to get the rounding in 5's not 1's.

floor(runif(50,20,50)/5)*5
 [1] 45 30 45 35 45 35 25 30 35 40 20 45 25 30 25 40 30 40 40 40 20 30 30 40 35 30 25 45 25 20 45 20 35 35 30 20 20 20 20 35 35 45 45 45 45 20
[47] 45 40 40 20

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM