R rbinom() Function - Generate Binomial Distribution Random Numbers

R 语言实例R Language Examples

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

The binomial distribution describes the number of successes in n independent trials, where the probability of success in each trial is p. It is often used to simulate scenarios such as coin tossing and quality inspection.

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

rbinom(n, size, prob)
dbinom(x, size, prob)   # 概率质量函数
pbinom(q, size, prob)   # 累积分布函数

Parameter description:

  • nNumber of random numbers to generate.

  • sizeNumber of trials.

  • probProbability of success on each trial.

Example

# Simulate 100 people tossing a coin 10 times, count the number of heads each person gets
set.seed(123)
coin_flips <- rbinom(100, size = 10, prob = 0.5)
print("Number of heads for the first 10 people:")
print(coin_flips[1:10])

# Count the distribution of the number of heads
print("Frequency table of head counts:")
print(table(coin_flips))

# dbinom: probability of getting exactly 6 heads when tossing a coin 10 times
prob_6 <- dbinom(6, size = 10, prob = 0.5)
print(paste("Probability of exactly 6 heads:", round(prob_6, 4)))

Executing the above code produces the following output:

[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 语言实例R Language Examples

Other Extensions