Skip to contents

this set of functions generates random bytes or numbers from OpenSSL. This provides a cryptographically secure alternative to R's default random number generator. rand_bytes generates n random cryptographically secure bytes

Usage

rand_bytes(n = 1)

rand_num(n = 1)

Arguments

n

number of random bytes or numbers to generate

Examples

rnd <- rand_bytes(10)
as.numeric(rnd)
#>  [1] 233  51 122 198   2 183 242 216 121 252
as.character(rnd)
#>  [1] "e9" "33" "7a" "c6" "02" "b7" "f2" "d8" "79" "fc"
as.logical(rawToBits(rnd))
#>  [1]  TRUE FALSE FALSE  TRUE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE
#> [13]  TRUE  TRUE FALSE FALSE FALSE  TRUE FALSE  TRUE  TRUE  TRUE  TRUE FALSE
#> [25] FALSE  TRUE  TRUE FALSE FALSE FALSE  TRUE  TRUE FALSE  TRUE FALSE FALSE
#> [37] FALSE FALSE FALSE FALSE  TRUE  TRUE  TRUE FALSE  TRUE  TRUE FALSE  TRUE
#> [49] FALSE  TRUE FALSE FALSE  TRUE  TRUE  TRUE  TRUE FALSE FALSE FALSE  TRUE
#> [61]  TRUE FALSE  TRUE  TRUE  TRUE FALSE FALSE  TRUE  TRUE  TRUE  TRUE FALSE
#> [73] FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE

# bytes range from 0 to 255
rnd <- rand_bytes(100000)
hist(as.numeric(rnd), breaks=-1:255)


# Generate random doubles between 0 and 1
rand_num(5)
#> [1] 0.18073264 0.90628335 0.04069838 0.35239623 0.23150688

# Use CDF to map [0,1] into random draws from a distribution
x <- qnorm(rand_num(1000), mean=100, sd=15)
hist(x)


y <- qbinom(rand_num(1000), size=10, prob=0.3)
hist(y)