R sample() Function - Random Sampling
The R sample() function is used to randomly draw elements from a vector.
sample() can simulate sampling with replacement, without replacement, and random shuffling; it 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:
-
x The vector to sample from.
-
size The number of elements to draw.
-
replace Whether to sample with replacement, FALSE by default (without replacement).
-
prob Optional; sampling probability weights for each element.
Example
Randomly draw 10 numbers from 1 to 100 (without replacement, often used for lottery draws)
set.seed
(
123
)
winners
<-
sample
(
1
:
100
, size
=
10
)
(
"Winning numbers:"
)
(
winners
)
Sampling with replacement (each draw independent, duplicates possible)
set.seed
(
123
)
dice_rolls
<-
sample
(
1
:
6
, size
=
10
,
replace
=
TRUE
)
(
"10 dice rolls:"
)
(
dice_rolls
)
The output of the code above is:
[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 (0.7 probability of heads, 0.3 of tails)
set.seed
(
123
)
biased_coin
<-
sample
(
c
(
"Heads"
,
"Tails"
)
, size
=
100
,
replace
=
TRUE, prob
=
c
(
0.7
,
0.3
)
)
(
"Proportions of 100 biased coin results:"
)
(
prop.table
(
table
(
biased_coin
)
)
)
The output of the code above is:
[1] "100 次有偏硬币结果比例:"
反面 正面
0.27 0.73
R Language Examples