concept binomial distribution in category R

This is an excerpt from Manning's book Practical Data Science with R, Second Edition.
This is similar to the linear regression call to lm(), with one additional argument: family = binomial(link = "logit"). The family function specifies the assumed distribution of the dependent variable y. In our case, we’re modeling y as a binomial distribution, or as a coin whose probability of heads depends on x. The link function “links” the output to a linear model—it’s as if you pass y through the link function, and then model the resulting value as a linear function of the x values. Different combinations of family functions and link functions lead to different kinds of generalized linear models (for example, Poisson, or probit). In this book, we’ll only discuss logistic models, so we’ll only need to use the binomial family with the logit link.[1]
Listing B.7. Plotting the binomial distribution
library(ggplot2) # # use dbinom to produce the theoretical curves # numflips <- 50 # x is the number of heads that we see x <- 0:numflips # probability of heads for several different coins p <- c(0.05, 0.15, 0.5, 0.75) plabels <- paste("p =", p) # calculate the probability of seeing x heads in numflips flips # for all the coins. This probably isn't the most elegant # way to do this, but at least it's easy to read flips <- NULL for(i in 1:length(p)) { coin <- p[i] label <- plabels[i] tmp <- data.frame(number_of_heads=x, probability = dbinom(x, numflips, coin), coin_type = label) flips <- rbind(flips, tmp) } # plot it # this is the plot that leads this section ggplot(flips, aes(x = number_of_heads, y = probability)) + geom_point(aes(color = coin_type, shape = coin_type)) + geom_line(aes(color = coin_type))
Listing B.10. Working with the binomial distribution
# pbinom example nflips <- 100 nheads <- c(25, 45, 50, 60) # number of heads # what are the probabilities of observing at most that # number of heads on a fair coin? left.tail <- pbinom(nheads, nflips, 0.5) sprintf("%2.2f", left.tail) # [1] "0.00" "0.18" "0.54" "0.98" # the probabilities of observing more than that # number of heads on a fair coin? right.tail <- pbinom(nheads, nflips, 0.5, lower.tail = FALSE) sprintf("%2.2f", right.tail) # [1] "1.00" "0.82" "0.46" "0.02" # as expected: left.tail+right.tail # [1] 1 1 1 1 # so if you flip a fair coin 100 times, # you are guaranteed to see more than 10 heads, # almost guaranteed to see fewer than 60, and # probably more than 45. # qbinom example nflips <- 100 # what's the 95% "central" interval of heads that you # would expect to observe on 100 flips of a fair coin? left.edge <- qbinom(0.025, nflips, 0.5) right.edge <- qbinom(0.025, nflips, 0.5, lower.tail = FALSE) c(left.edge, right.edge) # [1] 40 60 # so with 95% probability you should see between 40 and 60 heads