二項分佈

我們現在說明為二項分佈定義的函式 dbinompbinomqbinomrbinom

dbinom() 函式給出了二項式變數的各種值的概率。最低限度需要三個引數。此函式的第一個引數必須是分位數向量(隨機變數 X 的可能值)。第二個和第三個論點是分佈的 defining parameters,即 n(獨立試驗的數量)和 p(每個試驗成功的概率)。例如,對於使用 n = 5p = 0.5 的二項分佈,X 的可能值是 0,1,2,3,4,5。也就是說,dbinom(x,n,p) 函式給出了 x = 0, 1, 2, 3, 4, 5 的概率值 P( X = x )

#Binom(n = 5, p = 0.5) probabilities
> n <- 5; p<- 0.5; x <- 0:n
> dbinom(x,n,p)
[1] 0.03125 0.15625 0.31250 0.31250 0.15625 0.03125
#To verify the total probability is 1
> sum(dbinom(x,n,p))
[1] 1
> 

二項式概率分佈圖可以如下圖所示:

> x <- 0:12
> prob <- dbinom(x,12,.5)
> barplot(prob,col = "red",ylim = c(0,.2),names.arg=x,
                           main="Binomial Distribution\n(n=12,p=0.5)")

https://i.stack.imgur.com/cifQJ.jpg

注意,當 p = 0.5 時,二項分佈是對稱的。為了證明當 p 大於 0.5 時二項分佈是負偏差,請考慮以下示例:

> n=9; p=.7; x=0:n; prob=dbinom(x,n,p);
> barplot(prob,names.arg = x,main="Binomial Distribution\n(n=9, p=0.7)",col="lightblue")

https://i.stack.imgur.com/HvXyP.jpg

p 小於 0.5 時,二項分佈正偏斜,如下所示。

> n=9; p=.3; x=0:n; prob=dbinom(x,n,p); 
> barplot(prob,names.arg = x,main="Binomial Distribution\n(n=9, p=0.3)",col="cyan")

https://i.stack.imgur.com/dKqPx.jpg

我們現在將說明累積分佈函式 pbinom() 的用法。此函式可用於計算概率,例如 P( X <= x )。該函式的第一個引數是分位數向量(x 的值)。

# Calculating Probabilities
# P(X <= 2) in a Bin(n=5,p=0.5) distribution
> pbinom(2,5,0.5)
[1] 0.5

上述概率也可以如下獲得:

# P(X <= 2) = P(X=0) + P(X=1) + P(X=2)
> sum(dbinom(0:2,5,0.5))
[1] 0.5

要計算,型別的概率:P( a <= X <= b )

# P(3<= X <= 5) = P(X=3) + P(X=4) + P(X=5) in a Bin(n=9,p=0.6) dist
> sum(dbinom(c(3,4,5),9,0.6))
[1] 0.4923556
> 

以表格的形式呈現二項分佈:

> n = 10; p = 0.4; x = 0:n; 
> prob = dbinom(x,n,p) 
> cdf = pbinom(x,n,p) 
> distTable = cbind(x,prob,cdf)
> distTable
       x         prob         cdf
 [1,]  0 0.0060466176 0.006046618
 [2,]  1 0.0403107840 0.046357402
 [3,]  2 0.1209323520 0.167289754
 [4,]  3 0.2149908480 0.382280602
 [5,]  4 0.2508226560 0.633103258
 [6,]  5 0.2006581248 0.833761382
 [7,]  6 0.1114767360 0.945238118
 [8,]  7 0.0424673280 0.987705446
 [9,]  8 0.0106168320 0.998322278
[10,]  9 0.0015728640 0.999895142
[11,] 10 0.0001048576 1.000000000
> 

rbinom() 用於生成具有給定引數值的指定大小的隨機樣本。

# Simulation
> xVal<-names(table(rbinom(1000,8,.5)))
> barplot(as.vector(table(rbinom(1000,8,.5))),names.arg =xVal,
                    main="Simulated Binomial Distribution\n (n=8,p=0.5)")

https://i.stack.imgur.com/RNHh5.jpg