n <- 10 # Number of trials
p <- 0.6 # Probability of success
k <- 4 # Number of successes
choose(n, k) * p^k * (1 - p)^(n - k)[1] 0.1114767
Programming and Data Analysis with R
A random variable Y is a quantity whose value is not known in advance, such as the number of successes in 10 trials or tomorrow’s PM2.5 concentration. It is described by its cumulative distribution function F(y) = \mathbb{P}(Y \le y).
The probability mass function of a discrete random variable is f(y) = \mathbb{P}(Y = y), with f(y) \ge 0 and probabilities summing to 1.
The expected value of Y, and more generally of a transformation g(Y), is \mathbb{E}[Y] = \sum_y y \, f(y), \qquad \mathbb{E}[g(Y)] = \sum_y g(y) \, f(y).
Let Y \sim \text{binom}(n, \pi) be a binomial random variable, so that the probability mass function is \mathbb{P}(Y = k) = {n \choose k } \pi^k (1-\pi)^{n-k}, \qquad k=0,1,\dots,n.
Supposing that n = 10 and \pi = 0.6, then \mathbb{P}(Y=4) is computed as follows:
n <- 10 # Number of trials
p <- 0.6 # Probability of success
k <- 4 # Number of successes
choose(n, k) * p^k * (1 - p)^(n - k)[1] 0.1114767
However, in R there is a dedicated function to compute the probability mass function:
dbinom(k, size = n, prob = p)[1] 0.1114767
In a similar way, we can also compute the following probability, that is
F(y) = \mathbb{P}(Y \le y) = \sum_{k=0}^y\mathbb{P}(Y = k), \qquad Y \sim \text{binom}(n, \pi).
Supposing that n = 10 and \pi = 0.6, then the value F(5) is computed as follows:
sum(dbinom(0:5, size = n, prob = p))[1] 0.3668967
pbinom(5, size = n, prob = p) # Specific R function[1] 0.3668967
Suppose instead that we are interested in the complementary event, that is: \mathbb{P}(Y > 5) = 1 - \mathbb{P}(Y \le 5).
1 - pbinom(5, size = n, prob = p)[1] 0.6331033
pbinom(5, size = n, prob = p, lower.tail = FALSE)[1] 0.6331033
The expected value of a binomial random variable is equal to
\mathbb{E}[Y] = \sum_{k=0}^n k \: \mathbb{P}(Y = k) = n\pi, \qquad Y \sim \text{binom}(n,\pi).
Supposing as before that n = 10 and \pi = 0.6, we have that:
n * p # Expected value obtained through analytical computations[1] 6
sum(0:n * dbinom(0:n, size = n, prob = 0.6)) # Numerical computation[1] 6
Through direct computation, we can moreover evaluate for example \mathbb{E}[\sqrt{Y}], indeed:
sum(sqrt(0:n) * dbinom(0:n, size = n, prob = 0.6))[1] 2.427083
The p-quantile of a discrete distribution is the smallest value k such that \mathbb{P}(Y \le k) \ge p.
Supposing that Y \sim \text{binom}(10, 0.6), the first quartile is \mathcal{Q}_{0.25} = 5, because 5 is the smallest value k such that \mathbb{P}(Y \le k) \ge 0.25.
In R we can obtain these results as follows:
qbinom(0.25, size = 10, prob = 0.6) # First quartile[1] 5
Indeed, it holds that:
pbinom(4, size = 10, prob = 0.6) # The value is smaller than 0.25[1] 0.1662386
pbinom(5, size = 10, prob = 0.6) # The value is larger than 0.25[1] 0.3668967
kk <- 0:n
prob <- dbinom(0:n, size = n, prob = p)
plot(kk, prob, type = "h", main = "binom(10, 0.6)", xlab = "k", ylab = "P(Y=k)")
A random variable is said to be continuous if F(y) is continuous.
The density function of a continuous random variable is a function f(y) \ge 0 such that \mathbb{P}(a < Y < b) = \int_a^b f(y) \mathrm{d} y, \qquad f(y) = \frac{\mathrm{d}}{\mathrm{d} y} F(y).
Therefore, by definition: \mathbb{P}(Y \le b) = F(b) = \int_{-\infty}^b f(y) \mathrm{d} y.
Moreover, the expected value of a transformation g(Y), if it exists, is equal to \mathbb{E}[g(Y)] = \int_{\mathbb{R}} g(y) \: f(y) \mathrm{d} y.
Let Y \sim \text{N}(\mu, \sigma^2) be a Gaussian variable with mean \mu and variance \sigma^2, that is having density f(y) = \frac{1}{\sqrt{2 \pi \sigma^2}}\exp\left\{-\frac{1}{2\sigma^2}(y - \mu)^2\right\}.
If Y \sim \text{N}(3, 10) then we can compute the value f(1) using the R commands:
x <- 1 # Point at which to compute the density
mu <- 3 # Mean
sigma2 <- 10 # Variance
1 / sqrt(2 * pi * sigma2) * exp(-1 / (2 * sigma2) * (x - mu)^2)[1] 0.1032883
dnorm(x, mean = mu, sd = sqrt(sigma2))[1] 0.1032883
Let Y \sim \text{N}(0,1) be a standard normal. We are interested in computing the probability of the following event: \mathbb{P}(|Y| \le 1) = \mathbb{P}(-1 \le Y \le 1) = \mathbb{P}(Y \le 1) - \mathbb{P}(Y < -1).
We can compute this probability (in an inefficient way) through the command integrate, therefore:
integrate(dnorm, lower = -1, upper = 1)0.6826895 with absolute error < 7.6e-15
Since we are dealing with a continuous variable, we obtain that \mathbb{P}(Y < -1) = \mathbb{P}(Y \le -1).
Hence, we can compute this probability in R using the dedicated commands:
pnorm(1) - pnorm(-1)[1] 0.6826895
The continuity of the cumulative distribution function F(y) implies that the quantile function is equal to F^{-1}(\cdot), that is \mathcal{Q}_p = F^{-1}(p).
For example, consider the third quartile of a standard normal distribution, that is
qnorm(0.75)[1] 0.6744898
As a consequence, the quantile and the cumulative distribution functions are such that F(\mathcal{Q}_{0.75}) = F(F^{-1}(0.75))= 0.75.
Indeed:
pnorm(qnorm(0.75))[1] 0.75
curve(dnorm(x, mean = 0, sd = 1), from = -3, to = 3, ylab = "f(x)", main = "N(0,1)")
R has an extensive collection of functions dedicated to the main probability distributions. Let Y be a random variable.
ddist (where the initial d stands for density). Computes the density f(y) of a continuous variable Y, or the probability mass function f(y) = \mathbb{P}(Y = y) in case Y is discrete.
pdist (where the initial p stands for probability), which makes it possible to compute the value of the cumulative distribution function at a specified point, that is it computes F(y) = \mathbb{P}(Y \le y).
qdist (where the initial q stands for quantile), which represents the quantile function: it returns the value q such that \mathbb{P}(Y \le q) = p (for discrete variables, the smallest k such that \mathbb{P}(Y \le k) \ge p).
rdist (where the initial r stands for random), which makes it possible to generate pseudo-random numbers, illustrated below.
| Distribution | Command | Parameters | Default |
|---|---|---|---|
| Binomial | binom |
size, prob |
- |
| Geometric | geom |
prob |
- |
| Poisson | pois |
lambda |
- |
| Uniform | unif |
min, max |
0, 1 |
| Gamma | gamma |
shape, rate |
-, 1 |
| Exponential | exp |
rate |
1 |
| Chi-squared | chisq |
df |
- |
| Normal | norm |
mean, sd |
0, 1 |
The fourth class of functions in our list is the one of type rdist, which makes it possible to obtain random values from a distribution.
For example, to sample 5 independent and identically distributed (iid) values from a standard normal, that is Y_i \overset{\text{iid}}{\sim} \text{N}(0,1), \qquad i=1,\dots,5 we can use in R the following command:
set.seed(123) # Fixes the "seed", see below
R <- 5
rnorm(R, mean = 0, sd = 1)[1] -0.56047565 -0.23017749 1.55870831 0.07050839 0.12928774
The values generated by the command rdist imitate the results of a random process, but they are in fact deterministic. Such values are therefore called pseudo-random.
There actually exist methods to generate truly random numbers, based for instance on atmospheric measurements.
At the website https://www.random.org/gaussian-distributions/ it is possible to obtain a limited number of random values from a Gaussian distribution.
The disadvantage of this latter class of methods is that they are relatively expensive to obtain \implies is it worth it?
Unless there are specific security concerns, pseudo-random numbers are the standard used by almost all users.
A six-sided die represents a discrete random variable Y with probability mass function called Discrete Uniform, that is
\mathbb{P}(Y = k) = \frac{1}{6}, \qquad k=1,\dots,6.
To simulate the roll of a six-sided die, we first build a vector containing a sequence of numbers from 1 to 6 corresponding to the possible outcomes of the roll.
dice <- 1:6We can use the command sample to perform the roll:
set.seed(123) # R command to fix the "seed"
sample(x = dice, size = 1) # size = 1 implies that a single die is rolled[1] 3
sample commandMore generally, the function sample(x, size, replace, prob) randomly draws a number size of elements from an urn containing the objects x
replace = TRUE;replace = FALSE.If the argument prob is not specified, the function sample assigns equal probability to every element of x.
If we wanted to sample with non-uniform probabilities, we would have to provide a vector of probabilities of length equal to the number of elements of x.
Sampling with replacement is equivalent to making n independent draws from the same random variable Y. Therefore, to roll the same die 10 times:
set.seed(140)
n <- 10
# replace = TRUE implies that the die is rolled 10 times
sim <- sample(dice, size = n, replace = TRUE)
sim [1] 3 1 1 1 3 6 4 5 1 6
To perform a hypothetical lottery draw, one has to draw from an urn 5 numbers, between 1 and 90, without replacement.
In R therefore:
sample(1:90, size = 5, replace = FALSE)[1] 64 53 87 83 61
If we only specify the following command:
sample(dice)[1] 5 3 1 2 6 4
we obtain a random permutation of the elements of dice.
Indeed, the default values are replace = FALSE and size = length(x), that is a sampling without replacement of all the elements of the urn.