ZetCode

R random numbers

last modified November 19, 2026

Random numbers drive simulations, sampling, and games. R does not produce true randomness: it runs a deterministic algorithm called a pseudo-random number generator, which starts from a value called the seed and produces a long sequence of numbers that passes statistical tests for randomness. Because the algorithm is deterministic, the same seed always produces the same sequence, which is what makes random examples reproducible. This article covers sample, the uniform, normal, and binomial generators, weighted sampling, seeds, and a small simulation.

Drawing from a vector

The function sample draws values from a vector. Its first argument is the collection, the second is the number of draws, and the argument replace decides whether a value may be drawn more than once. Without replacement, the draws are a shuffled selection of distinct elements; with replacement, every draw is independent. The next script rolls a die ten times.

drawing.R
set.seed(42)
dice <- sample(1:6, 10, replace = TRUE)
cat("rolls:", dice, "\n")
cat("total:", sum(dice), "\n")

The vector 1:6 represents the six faces, and replace = TRUE allows the same face to appear again. The ten results are one possible outcome; a different seed would produce a different sequence. sum adds the rolls, which is the total shown by the second line.

$ Rscript drawing.R
rolls: 1 5 1 1 2 4 2 2 1 4 
total: 23 

Seeds and reproducibility

set.seed resets the generator to a known state. Two sessions that call set.seed with the same number and then run the same calls receive the same values. This is essential for examples, tests, and any simulation whose result must be checked later; without a seed, the output changes on every run.

seeding.R
set.seed(123)
first <- runif(3)
set.seed(123)
second <- runif(3)
cat("first:", first, "\n")
cat("second:", second, "\n")
cat("same:", identical(first, second), "\n")

The two vectors are identical because the second set.seed(123) returns the generator to the state it had before the first three draws. In a script, place one seed near the top and record it in a comment, so that a reader can reproduce the whole run. R itself may change the default generator in a new major release, so a seed is reproducible only with the same R version and the same generator.

$ Rscript seeding.R
first: 0.2875775 0.7883051 0.4089769 
second: 0.2875775 0.7883051 0.4089769 
same: TRUE 

Uniform numbers

runif draws from the uniform distribution, in which every value in an interval is equally likely. The first argument is the number of draws, and min and max set the interval. The default interval is zero to one, which is convenient for probabilities and for simulations on the unit square.

uniform.R
set.seed(7)
x <- runif(5, min = 10, max = 20)
cat("values:", round(x, 2), "\n")
cat("range:", range(x), "\n")

All five values lie between ten and twenty, as requested. range returns the smallest and largest value of a vector, which is a quick check that the draws respect the bounds. round changes only the printed values; the stored numbers keep full precision.

$ Rscript uniform.R
values: 19.89 13.98 11.16 10.7 12.44 
range: 10.69749 19.88909 

Normal numbers

rnorm draws from the normal distribution, the familiar bell-shaped curve. Its arguments are the number of draws, the mean, and the standard deviation, a measure of how far values typically lie from the mean. The default is the standard normal distribution with mean zero and standard deviation one.

normal.R
set.seed(2024)
heights <- rnorm(6, mean = 170, sd = 8)
cat("heights:", round(heights, 1), "\n")
cat("mean:", round(mean(heights), 1), "\n")
cat("sd:", round(sd(heights), 1), "\n")

The sample mean and standard deviation are close to the requested 170 and 8, but not equal to them: six observations are a small sample, and every sample varies around its population. Increasing the number of draws narrows the difference. The functions mean and sd compute the statistics of the sample, not of the distribution.

$ Rscript normal.R
heights: 177.9 173.7 169.1 168.3 179.3 180.3 
mean: 174.8 
sd: 5.2 

Binomial draws

rbinom counts successes in a fixed number of independent trials. Its arguments are the number of experiments, the number of trials in each experiment, and the probability of success on one trial. One call can therefore simulate ten people each flipping ten coins, or ten days each with ten customers.

binomial-draws.R
set.seed(11)
heads <- rbinom(10, size = 10, prob = 0.5)
cat("heads:", heads, "\n")

Each value is a count between zero and ten, and the values cluster around five, the expected number of heads in ten fair flips. A single value such as eight is unusual but not impossible. The same function with size = 1 draws zeros and ones, which is a convenient way to simulate a binary outcome.

$ Rscript binomial-draws.R
heads: 4 0 5 2 3 8 3 4 7 3 

Weighted sampling

The argument prob gives each element a probability of being drawn. The probabilities do not have to sum to one; R normalises them internally. With replacement, every draw uses the same weights, so a rare element can still appear several times in a short run.

weighted.R
set.seed(5)
prize <- sample(c("gold", "silver", "bronze"), 8, replace = TRUE,
                prob = c(0.1, 0.3, 0.6))
print(prize)

Bronze has the largest weight, so it appears most often in this sample, but the order is still random and a gold prize can appear early. Without replace = TRUE, the weights apply to the first draw and are then adjusted for the remaining elements, which is how a raffle without repeats works.

$ Rscript weighted.R
[1] "bronze" "silver" "gold"   "bronze" "bronze" "silver" "bronze" "silver"

A simulation

A Monte Carlo simulation estimates a quantity by drawing random samples and averaging the results. The next script estimates pi. It draws points inside the unit square and counts how many fall inside the quarter circle of radius one, whose area is pi divided by four. Four times the proportion inside is therefore an estimate of pi.

montecarlo.R
set.seed(99)
n <- 10000
x <- runif(n)
y <- runif(n)
inside <- x^2 + y^2 <= 1
estimate <- 4 * mean(inside)
cat("estimate:", estimate, "\n")

The condition x^2 + y^2 <= 1 is vectorised over all ten thousand points, and mean turns the logical vector into a proportion. The estimate is close to 3.14 but not exact, and a different seed would move the last digits. The error decreases slowly, roughly with the square root of the number of points, so doubling the precision needs four times as many draws.

$ Rscript montecarlo.R
estimate: 3.1584 

Random number generators

RNGkind reports or changes the generator. The default in R 4.5 is the Mersenne-Twister generator, with inversion for normal deviates and rejection for the sampling done by sample. Other generators exist for parallel work and for reproducing results from older versions of R.

generators.R
print(RNGkind())
set.seed(1)
print(runif(3))
RNGkind("L'Ecuyer-CMRG")
set.seed(1)
print(runif(3))

The first line lists the three choices, the second shows the stream of the default generator after set.seed(1), and the third shows the same seed with the L'Ecuyer generator, which produces different values. Changing the generator in the middle of a simulation invalidates the earlier draws, so set the kind once at the start, before the seed. Most scripts never need to change it at all.

$ Rscript generators.R
[1] "Mersenne-Twister" "Inversion"        "Rejection"       
[1] 0.2655087 0.3721239 0.5728534
[1] 0.6775328 0.4273457 0.9103805

A complete example

The next script simulates a simple game. A player pays one unit per round, rolls a die, and receives two units when the roll is five or six. The variable wins marks the winning rounds, and the payout subtracts the stake of every round from the prize money.

dicegame.R
set.seed(17)
n <- 1000
rolls <- sample(1:6, n, replace = TRUE)
wins <- rolls >= 5
cat("wins:", sum(wins), "\n")
cat("win rate:", mean(wins), "\n")
cat("payout:", sum(wins) * 2 - n, "\n")

The win rate is close to one third, the probability of rolling a five or a six, and the payout is negative because the prize is only twice the stake. In the long run the player loses about one third of a unit per round. The exact result depends on the seed; the direction of the game does not.

$ Rscript dicegame.R
wins: 344 
win rate: 0.344 
payout: -312 

Next steps

The vectors article explains how to store and index the values these functions produce, and the distributions article later in the series adds the density, distribution, and quantile functions that belong to the same families. The descriptive statistics article shows how to summarise simulated data, and the hypothesis testing article uses random draws to check how often a test reaches the wrong conclusion.

Source

An Introduction to R: probability distributions

R documentation: random number generation

R documentation: sample

In this article we have drawn values with sample, made runs reproducible with set.seed, and used the uniform, normal, and binomial generators. We sampled with weights, estimated pi with a Monte Carlo simulation, inspected RNGkind, and simulated a game whose expected result is a loss. The series continues with R vectors.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all R Language tutorials.