Ad space (banner)
๐Ÿ“ŠR Lessons
Lesson 53 / 68

Generating random numbers

This lesson covers generating random numbers with R's sample, with the aim of building things with a random element such as dice or rock-paper-scissors.

sample() picks values at random from a range or a vector. Use it for dice, lotteries, and the like — the result changes on every run.

The sample code picks a dice roll from 1 to 6 with sample(1:6, 1) and one of Rock, Scissors, or Paper from a vector with sample(choices, 1). Note the second argument, which says how many to pick.

A common early stumble is reproducibility. Tests sometimes need the same result every time, and set.seed() fixes the random seed to make that possible.

In professional work, sample is used widely in areas R excels at — statistical sampling and simulation.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run R directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)