1 min read

Randomness in R

https://blog.revolutionanalytics.com/2009/02/how-to-choose-a-random-number-in-r.html

Generate random numbers between 0 and 1

runif(1,0,1) # 1 random number
runif(5,0,1) # 5 random numbers

Generate random integers between 1 and 100

sample(x = 100, size = 1, replace = TRUE) # x = 100 means between 1 and 100
sample(x = 100, size = 5, replace = TRUE) # 5 random numbers
sample(x = 100, size = 5, replace = FALSE) # 5 random numbers, without replacement
sample(x = 50:100, size = 5, replace = TRUE) # 5 random numbers between 50 and 100

Select random items from a list

sample(x = state.name, size = 1, replace = FALSE)
sample(x = state.name, size = 5, replace = FALSE)

Randomly order a list

sample(x = 1:10, size = 10, replace = FALSE)

Roll a cube with 4 ‘R’ and 2 ‘G’ 3 times. Do this 1000 times and list the likelihood of each possible sequence.

cube = c('R','R','R','R','G','G')
n_iter = 1000
round <- function() { paste(sample(x = cube, size = 4, replace = TRUE),
                            collapse = '') }

table(replicate(n_iter, round())) / n_iter