Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R sample() Function - Random Sampling

R sample() Function - Random Sampling

R Language Examples R Language Examples

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:

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

)

print

(

"Winning numbers:"

)

print

(

winners

)

Sampling with replacement (each draw independent, duplicates possible)

set.seed

(

123

)

dice_rolls

<-

sample

(

1

:

6

, size

=

10

,

replace

=

TRUE

)

print

(

"10 dice rolls:"

)

print

(

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

)

)

print

(

"Proportions of 100 biased coin results:"

)

print

(

prop.table

(

table

(

biased_coin

)

)

)

The output of the code above is:

[1] "100 次有偏硬币结果比例:"

反面 正面

0.27 0.73

R Language Examples R Language Examples