### Computing binomial probabilities

Let $$X \sim bin(n, \pi)$$. If you are interested in computing $$P(X = x), \forall x = 0, \ldots, k$$, you can exploit the dbinom function, but you can try to define your own-made binomial distribution exploiting the extensible nature of R.

Here is your hand-made binomial function (remember that choose returns the binomial coefficient):

bs_dbinom <- function(x, n, pi){
choose(n, x) * pi ^ x * (1- pi) ^ (n - x)
}

Your function is ready to use. Here is the call using the “by position” calling style:

bs_dbinom(0, 10, 0.1)
## [1] 0.3486784

and here the call using the “by name” calling style:

bs_dbinom(x = 0, n = 10, pi = 0.1)
## [1] 0.3486784

The bs_dbinom function is vectorized, as the internal dbinom:

bs_dbinom(0:10, 10, 0.1)
##  [1] 0.3486784401 0.3874204890 0.1937102445 0.0573956280 0.0111602610
##  [6] 0.0014880348 0.0001377810 0.0000087480 0.0000003645 0.0000000090
## [11] 0.0000000001

You can compare your hand-made function with the dbinom R function:

dbinom(0, 10, 0.1)
## [1] 0.3486784
bs_dbinom(0, 10, 0.1)
## [1] 0.3486784

Follows a whole comparison on all the possible $$x$$ values:

dbinom(0:10, 10, 0.1)
##  [1] 0.3486784401 0.3874204890 0.1937102445 0.0573956280 0.0111602610
##  [6] 0.0014880348 0.0001377810 0.0000087480 0.0000003645 0.0000000090
## [11] 0.0000000001
bs_dbinom(0:10, 10, 0.1)
##  [1] 0.3486784401 0.3874204890 0.1937102445 0.0573956280 0.0111602610
##  [6] 0.0014880348 0.0001377810 0.0000087480 0.0000003645 0.0000000090
## [11] 0.0000000001

cbind(x = 0:10, dbinom = dbinom(0:10, 10, 0.1), bs_dbinom = bs_dbinom(0:10, 10, 0.1))
##        x       dbinom    bs_dbinom
##  [1,]  0 0.3486784401 0.3486784401
##  [2,]  1 0.3874204890 0.3874204890
##  [3,]  2 0.1937102445 0.1937102445
##  [4,]  3 0.0573956280 0.0573956280
##  [5,]  4 0.0111602610 0.0111602610
##  [6,]  5 0.0014880348 0.0014880348
##  [7,]  6 0.0001377810 0.0001377810
##  [8,]  7 0.0000087480 0.0000087480
##  [9,]  8 0.0000003645 0.0000003645
## [10,]  9 0.0000000090 0.0000000090
## [11,] 10 0.0000000001 0.0000000001