← Back to R Course | Chapter 9: Statistics | Lesson 5 of 7

sample()

sample picks items at random from a list, like pulling names out of a hat. You say how many to draw.

In this page:

  1. sample()
Syntax
r
sample(x, size)
sample(x, size, replace = TRUE)

sample()

sample(x, size) randomly draws size elements from a vector x, without replacement by default -- pass replace = TRUE to allow repeats.

It's used for random sampling, shuffling, and simulation. Combined with set.seed(), sampling results become reproducible.

Note: sample(x) with no size argument, and size equal to length(x), effectively shuffles the whole vector.

Example: sample()

markup
set.seed(42)
values <- 1:10

drawn <- sample(values, 3)
print(drawn)

shuffled <- sample(values)
print(shuffled)
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Sampling more items than exist without replace = TRUE, as in sample(1:10, 20), which gives an error.
  2. Calling sample(5) on a single number and getting a shuffle of 1:5, when it may not be intended.
  3. Expecting the same result each run, when you need set.seed() for reproducibility.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.