Random Numbers in R Programming Language

Here’s the translation of the Go random numbers example to R, formatted in Markdown suitable for Hugo:

R provides several functions for generating random numbers through its built-in stats package.

# For reproducibility, we set a seed
set.seed(42)

# Generate random integers between 0 and 99
cat(sample(0:99, 2, replace = TRUE), "\n")

# Generate a random number between 0 and 1
cat(runif(1), "\n")

# Generate random numbers between 5 and 10
cat(runif(2, 5, 10), "\n")

# Create a custom random number generator
custom_rng <- function(seed) {
  set.seed(seed)
  function(n) sample(0:99, n, replace = TRUE)
}

rng1 <- custom_rng(42)
cat(rng1(2), "\n")

rng2 <- custom_rng(42)
cat(rng2(2), "\n")

Let’s break down the R equivalent of the random number generation:

  1. R doesn’t require explicit package imports for basic random number generation.

  2. We use set.seed(42) to initialize the random number generator for reproducibility.

  3. sample(0:99, 2, replace = TRUE) generates two random integers between 0 and 99.

  4. runif(1) generates a random float between 0 and 1.

  5. runif(2, 5, 10) generates two random floats between 5 and 10.

  6. To create a custom random number generator, we define a function custom_rng that takes a seed and returns a function for generating random numbers.

  7. We create two instances of our custom random number generator with the same seed to demonstrate that they produce the same sequence of numbers.

When you run this script, you might see output similar to this:

49 68 
0.9148060 
7.937075 9.041002 
49 68 
49 68 

Note that the exact numbers may vary due to differences in random number generation algorithms between R and other languages.

R’s stats package provides many more functions for various random distributions. You can explore more in the R documentation for random number generation.