sample()

sample(x, size, replace = FALSE, prob = NULL)
Returns: vector of same type as x · Updated March 13, 2026 · Base Functions
random sampling base

The sample() function randomly selects elements from a vector. It is essential for simulations, bootstrap resampling, creating train/test splits for machine learning, and randomizing order. By default, it performs sampling without replacement, meaning each element can only be selected once.

Syntax

sample(x, size, replace = FALSE, prob = NULL)

Parameters

ParameterTypeDefaultDescription
xvectorA vector from which to sample
sizeintegerNumber of elements to sample; must not exceed length of x unless replace = TRUE
replacelogicalFALSEIf TRUE, elements can be sampled multiple times
probnumeric vectorNULLA vector of probabilities for sampling each element; must sum to 1

Examples

Basic usage

# Sample 3 elements from a vector without replacement
sample(1:10, 3)
# [1] 4 2 9

# Sample with replacement (allows repeats)
sample(1:3, 10, replace = TRUE)
# [1] 1 3 1 2 1 3 2 1 1 2

Randomizing vector order

# Shuffle a vector by sampling all elements
x <- c("a", "b", "c", "d", "e")
sample(x)
# [1] "c" "a" "e" "d" "b"

# Equivalent to sample(x, length(x))
sample(x)
# [1] "b" "d" "a" "e" "c"

Weighted sampling

# Sample with custom probabilities
sample(c("low", "medium", "high"), 1000, 
       replace = TRUE, 
       prob = c(0.5, 0.3, 0.2))

table(sample(c("low", "medium", "high"), 1000, 
             replace = TRUE, 
             prob = c(0.5, 0.3, 0.2)))
#    high     low  medium 
#     196     491     313

Common Patterns

Train/test split: Randomly partition data into training and testing sets.

set.seed(42)
data <- data.frame(x = 1:100, y = rnorm(100))

indices <- sample(nrow(data), size = 0.8 * nrow(data))
train <- data[indices, ]
test <- data[-indices, ]

nrow(train)  # 80
nrow(test)   # 20

Bootstrap resampling: Sample with replacement to create bootstrap samples.

set.seed(123)
original <- c(10, 20, 30, 40, 50)

# Create 3 bootstrap samples
bootstrap_samples <- replicate(3, sample(original, replace = TRUE))
bootstrap_samples
#      [,1] [,2] [,3]
# [1,]   40   20   40
# [2,]   40   50   20
# [3,]   20   30   10
# [4,]   10   40   50
# [5,]   50   10   30

Random password generation: Generate random strings from character sets.

chars <- c(letters, LETTERS, 0:9)
set.seed(42)
password <- paste0(sample(chars, 8, replace = TRUE), collapse = "")
password
# [1] "xK7Pm3nQ"

See Also