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

R rbinom() Function - Generating Binomial Random Numbers

R rbinom() Function - Generating Binomial Random Numbers

R Language Examples R Language Examples

The R rbinom() function is used to generate random numbers following a binomial distribution.

The binomial distribution describes the number of successes in n independent trials, each with success probability p. It is often used to simulate coin tosses, quality sampling, and similar scenarios.

The syntax of the rbinom() function is as follows:

rbinom(n, size, prob)

dbinom(x, size, prob)   # 概率质量函数

pbinom(q, size, prob)   # 累积分布函数

Parameter Description:

Example

Simulate 100 people tossing a coin 10 times, counting how many heads each person gets

set.seed

(

123

)

coin_flips

<-

rbinom

(

100

, size

=

10

, prob

=

0.5

)

print

(

"Heads counts for the first 10 people:"

)

print

(

coin_flips

[

1

:

10

]

)

Count the distribution of heads

print

(

"Frequency table of heads counts:"

)

print

(

table

(

coin_flips

)

)

dbinom: probability of getting exactly 6 heads in 10 tosses

prob_6

<-

dbinom

(

6

, size

=

10

, prob

=

0.5

)

print

(

paste

(

"Probability of exactly 6 heads:"

,

round

(

prob_6,

4

)

)

)

The output of the code above is:

[1] "前 10 人的正面次数:"

 [1] 5 7 8 4 5 6 5 7 6 2

[1] "正面次数频数表:"

 0  1  2  3  4  5  6  7  8  9 10

 1  1  1  9 11 17 24 22  8  5  1

[1] "恰好 6 次正面的概率: 0.2051"

R Language Examples R Language Examples