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

sample()

In this page:

  1. sample()

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)
🔒

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.