R sample() Function - Random Sampling
The R sample() function is used to randomly draw elements from a vector.
sample() can simulate sampling with replacement, sampling without replacement, and random shuffling, and is widely used in data sampling and experimental design.
The syntax of the sample() function is as follows:
sample(x, size, replace = FALSE, prob = NULL)
Parameter description:
xThe vector to be sampled.
sizeThe number of elements to draw.
replaceWhether to sample with replacement; default is FALSE (without replacement).
probOptional, the sampling probability weight of each element.
Example
# Randomly draw 10 from 1 to 100 (without replacement, commonly used for random lottery draws)
set.seed(123)
winners <- sample(1:100, size = 10)
print("Winning numbers:")
print(winners)
# Sampling with replacement (independent each time, duplicates possible)
set.seed(123)
dice_rolls <- sample(1:6, size = 10, replace = TRUE)
print("Roll the dice 10 times:")
print(dice_rolls)
set.seed(123)
winners <- sample(1:100, size = 10)
print("Winning numbers:")
print(winners)
# Sampling with replacement (independent each time, duplicates possible)
set.seed(123)
dice_rolls <- sample(1:6, size = 10, replace = TRUE)
print("Roll the dice 10 times:")
print(dice_rolls)
Executing the above code produces the following output:
[1] "中奖号码:" [1] 31 79 51 14 67 42 50 43 97 25 [1] "掷 10 次骰子:" [1] 6 1 4 2 2 1 4 5 5 1
Unequal sampling probabilities can be set through the prob parameter:
Example
# Simulate an unbalanced coin (heads probability 0.7, tails 0.3)
set.seed(123)
biased_coin <- sample(c("Heads", "Tails"), size = 100,
replace = TRUE, prob = c(0.7, 0.3))
print("Proportion of results from 100 biased coin tosses:")
print(prop.table(table(biased_coin)))
set.seed(123)
biased_coin <- sample(c("Heads", "Tails"), size = 100,
replace = TRUE, prob = c(0.7, 0.3))
print("Proportion of results from 100 biased coin tosses:")
print(prop.table(table(biased_coin)))
Executing the above code produces the following output:
[1] "100 次有偏硬币结果比例:" 反面 正面 0.27 0.73Other Extensions
R Language Examples