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:
Syntax
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()
set.seed(42)
values <- 1:10
drawn <- sample(values, 3)
print(drawn)
shuffled <- sample(values)
print(shuffled)
Login to try C/C++/Java/PHP code in the editor
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
- Sampling more items than exist without
replace = TRUE, as insample(1:10, 20), which gives an error. - Calling
sample(5)on a single number and getting a shuffle of1:5, when it may not be intended. - 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: