Sampling

Suppose you are the lottery fairy in a weekly lottery, where 6 out of 49 unique numbers are drawn

# Instructions:

Draw the winning numbers for this week

sample(1:49, size = 6)
[1] 19 46 14  5 29  7

Probability Density Function

# Instructions:

Consider a random variable X with probability density function (PDF)

# define the PDF
f <- function(x){x/4*exp(-x^2/8)}

# integrate f over the domain
integrate(f, 0, Inf)$value
[1] 1

Expected Value and Variance

# Instructions

Define a suitable function ex() which integrates to the expected value of X

# define the function ex
ex <- function(x){x*f(x)}

Compute the expected value of X. Store the result in expected_value.

# compute the expected value of X
expected_value <- integrate(ex, 0, Inf)$value

Define a suitable function ex2() which integrates to the expected value of X2

# define the function ex2
ex2 <- function(x){x^2*f(x)}

Compute the variance of X. Store the result in variance

# compute the variance of X
variance <- integrate(ex2, 0, Inf)$value - expected_value^2

Standard Normal Distribution I

# Instructions

Compute ϕ(3), that is, the value of the standard normal density at c=3.

# compute the value of the standard normal density at c=3
dnorm(3)
[1] 0.004431848

Standard Normal Distribution II

# Instructions

Compute P(|Z|≤1.64) by using the function pnorm()

# compute the probability
pnorm(1.64)-pnorm(-1.64)
[1] 0.8989948

Normal Distributions

# Instructions

# compute the probability
pnorm(1.64)-pnorm(-1.64)
[1] 0.8989948

Normal Distribution II

# Instructions

Generate 10 random numbers from this distribution (2,12)

set.seed(123)
# generate 10 random numbers from the given distribution.
rnorm(10, mean = 2, sd = sqrt(12))
 [1]  0.05845541  1.20264179  7.39952399  2.24424823  2.44786585  7.94115939
 [7]  3.59666057 -2.38230067 -0.37932807  0.45618165

Chi-squared Distribution I

# Instructions

Plot the corresponding PDF using curve(). Specify the range of x-values as [0,25] via the argument xlim

# plot the PDF of a chi^2 random variable with df = 10
curve(dchisq(x, df = 10), xlim = c(0, 25))

Chi-squared Distribution II

# Instructions

# compute the probability
pchisq(10/15, df = 2, lower.tail = F)
[1] 0.7165313

Student t Distribution I

# compute the 95% quantile of a t distribution with 10000 degrees of freedom
qt(0.95, df = 10000)
[1] 1.645006
# compute the 95% quantile of a standard normal distribution
qnorm(0.95)
[1] 1.644854

Student t Distribution II

# Instructions

set.seed(123)
# generate 1000 random numbers from the given distribution. Assign them to the variable x.
x <- rt(1000, df = 1)
# compute the sample mean of x.
mean(x)
[1] 11.03422

F Distribution I

# Instructions

# plot the quantile function of the given distribution
curve(qf(x, df1 = 10, df2 = 4))

F Distribution II

# Instructions

# compute the probability by integration
integrate(df, lower = 1, upper = 10, df1 = 4, df2 = 5)$value
[1] 0.472397