# INFOMAAT - Statistics Module I - Practice exam (Mock 3)
# R script with the solution of the exercises

## EXERCISE 1

# Download coworking.RData, save it in the same folder as this script and set the
# working directory (Session -> Set Working Directory -> To Source File Location).
# load() restores the data frame "coworking_dataset" in your workspace.

load("coworking.RData")

attach(coworking_dataset)
n = nrow(coworking_dataset)
n

#####
# 1 #
#####

# Comfort is qualitative ORDINAL: order the levels before building the tables
Comfort = factor(Comfort, levels = c("Basic", "Standard", "Premium"))

table(Comfort)               # absolute frequencies
table(Comfort)/n             # relative frequencies
cumsum(table(Comfort)/n)     # cumulative relative frequencies F_j

barplot(table(Comfort)/n)    # bar chart (relative frequencies)

# Median: first value with F_j >= 0.5 (read it from the cumulative frequencies)

#####
# 2 #
#####

meanP_T = mean(Price[City == "Turin"])      # mean of Price in Turin
meanP_B = mean(Price[City == "Bologna"])    # mean of Price in Bologna
meanP_T; meanP_B

sdP_T = sd(Price[City == "Turin"])          # unbiased standard deviation, Turin
sdP_B = sd(Price[City == "Bologna"])
sdP_T; sdP_B

v_T = sdP_T / abs(meanP_T)                  # coefficient of variation, Turin
v_B = sdP_B / abs(meanP_B)
v_T; v_B

#####
# 3 #
#####

table(Comfort, City)                        # contingency table
addmargins(table(Comfort, City))            # with marginal frequencies
addmargins(table(Comfort, City)/n)          # relative frequencies with marginals

chiObj = chisq.test(Comfort, City)          # chi-squared object
chiObj$statistic                            # chi-squared statistic
chiObj$expected                             # expected counts under independence

chiMax = n*(min(3, 2) - 1)                  # maximum value of the chi-squared
chiMax
normChi = chiObj$statistic / chiMax         # normalized chi-squared
normChi

#####
# 4 #
#####

plot(Members, Price)                        # scatter plot

cov(Members, Price)                         # unbiased covariance
cor(Members, Price)                         # correlation coefficient

## EXERCISE 2  (R used only as a calculator)

# A, B, C = supplier; D = "the component is defective"
P_A = 0.50; P_B = 0.30; P_C = 0.20
P_D_A = 0.01; P_D_B = 0.02; P_D_C = 0.05

#####
# 1 #
#####

# Law of total probability
P_D = P_D_A*P_A + P_D_B*P_B + P_D_C*P_C
P_D

#####
# 2 #
#####

# Bayes' theorem
P_D_C*P_C / P_D                             # P(C | D)

#####
# 3 #
#####

# X ~ Bin(n = 10, p = P(D)); P(X <= 1) = P(X = 0) + P(X = 1)
pbinom(q = 1, size = 10, prob = P_D)

# the same by hand
(1 - P_D)^10 + 10 * P_D * (1 - P_D)^9
