R Functions Related to Discrete Random Variables

One can easily simulate a discrete probability distribution in R, as well as find its expected value (mean) and variance. Consider the following calculations in R related to a random variable $X$ described by $$\begin{array}{l|c|c|c|c} X & -4 & 2 & 5 & 10\\\hline P(X) & 0.50 & 0.30 & 0.15 & 0.05 \end{array}$$

> X.outcomes = c(-4,2,5,10)
> X.probabilities = c(0.50,0.30,0.15,0.05)

> # to simulate 10 outcomes...
> sample(X.outcomes, 10, replace = TRUE, prob = X.probabilities)
 [1]  2 -4 -4 -4 -4 -4  2  5 -4  2
 
> # to find the expected value (remember that vector multiplication is done pair-wise)
> X.expectedValue = sum(X.outcomes * X.probabilities)
> X.expectedValue
[1] -0.15

> # to calculate the variance
> X.variance = sum(X.outcomes^2 * X.probabilities) - X.expectedValue^2
> X.variance
[1] 17.9275

> X.standardDeviation = sqrt(X.variance)
> X.standardDeviation
[1] 4.234088