setwd("C:/Users/Dell/OneDrive/Desktop/Submit-Academy/Discussion_2_R_Notebook")
installed packages as described in the getting started on R document
library(knitr)
library(rmarkdown)
library(mosaic)
## Registered S3 method overwritten by 'mosaic':
## method from
## fortify.SpatialPolygonsDataFrame ggplot2
##
## The 'mosaic' package masks several functions from core packages in order to add
## additional features. The original behavior of these functions should not be affected by this.
##
## Attaching package: 'mosaic'
## The following objects are masked from 'package:dplyr':
##
## count, do, tally
## The following object is masked from 'package:Matrix':
##
## mean
## The following object is masked from 'package:ggplot2':
##
## stat
## The following objects are masked from 'package:stats':
##
## binom.test, cor, cor.test, cov, fivenum, IQR, median, prop.test,
## quantile, sd, t.test, var
## The following objects are masked from 'package:base':
##
## max, mean, min, prod, range, sample, sum
library(readxl)
Bweight <- read_excel("Bweight.xlsx")
head(Bweight)
*** Question1*** (1) Create a crosstab (i.e., contingency table) with the absolute frequencies (counts) for the pair of variables “smoke” and “first”. What is the mode of this pair of variables? Formulate your answer in a single sentence that is suitable for a broad audience.
# Crosstab of absolute frequencies
tab <- table(Smoke = Bweight$smoke, First = Bweight$first)
tab
## First
## Smoke 0 1
## 0 521 447
## 1 30 28
## 2 56 28
## 3 64 26
addmargins(tab)
## First
## Smoke 0 1 Sum
## 0 521 447 968
## 1 30 28 58
## 2 56 28 84
## 3 64 26 90
## Sum 671 529 1200
# Mode of the pair = the cell with the highest count (ties are all shown)
idx <- which(tab == max(tab), arr.ind = TRUE)
for (i in seq_len(nrow(idx))) {
cat(sprintf(
"The most common combination is smoke = '%s' and first = '%s', which occurs %d times out of %d cases.\n",
rownames(tab)[idx[i, 1]], colnames(tab)[idx[i, 2]], max(tab), sum(tab)
))
}
## The most common combination is smoke = '0' and first = '0', which occurs 521 times out of 1200 cases.
*** Question 2*** 2) Compare the ages of the unmarried mothers with the ages of the married mothers by drawing two boxplots on the same graph. Let the relative dispersion be represented by (q3 - q1) / q2 where is the -th quartile ( =0,1,2,3,4). Where is the dispersion of the ages relatively the largest: in the ages of the unmarried mothers or in the ages of the married mothers? Present your numerical results in a table
Crosstab of absolute frequencies
``` r
Bweight$married_f <- factor(Bweight$married, levels = c(0, 1),
labels = c("Unmarried", "Married"))
Two boxplots on the same graph):
boxplot(age ~ married_f, data = Bweight,
main = "Age of mothers by marital status",
xlab = "Marital status", ylab = "Age of mother (years)",
col = c("lightgreen", "lightblue"))
Quartiles q0..q4 and relative dispersion (q3 - q1) / q2
res <- do.call(rbind, lapply(split(Bweight$age, Bweight$married_f), function(x) {
q <- quantile(x, probs = c(0, 0.25, 0.5, 0.75, 1))
c(n = length(x), q0 = q[[1]], q1 = q[[2]], q2 = q[[3]],
q3 = q[[4]], q4 = q[[5]], rel_disp = (q[[4]] - q[[2]]) / q[[3]])
}))
round(res, 3)
## n q0 q1 q2 q3 q4 rel_disp
## Unmarried 342 14 19 22 26 41 0.318
## Married 858 15 25 28 31 44 0.214
Unmarried mothers: the middle 50% of ages spans 7 years (19 to 26). That is about 32% of their median age of 22. Married mothers: the middle 50% spans 6 years (25 to 31). That is only about 21% of their median age of 28.
3)*** Draw the scatterplot with the variable “age” on the horizontal axis and the variable “weight” on the vertical axis. Add to this plot the estimated (least-squares) regression line of “weight” on “age”.
Least-squares regression of weight on age
fit <- lm(weight ~ age, data = Bweight)
coef(fit)
## (Intercept) age
## 3024.76572 12.96893
summary(fit)
##
## Call:
## lm(formula = weight ~ age, data = Bweight)
##
## Residuals:
## Min 1Q Median 3Q Max
## -2939.02 -325.90 20.62 370.30 1921.29
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 3024.77 83.89 36.054 < 2e-16 ***
## age 12.97 3.09 4.197 2.91e-05 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 593.4 on 1198 degrees of freedom
## Multiple R-squared: 0.01449, Adjusted R-squared: 0.01367
## F-statistic: 17.61 on 1 and 1198 DF, p-value: 2.909e-05
Scatterplot with the regression line
plot(Bweight$age, Bweight$weight,
xlab = "Age of mother (years)", ylab = "Birth weight (grams)",
main = "Birth weight vs. mother's age",
pch = 16, col = rgb(0, 0, 1, 0.4))
abline(fit, col = "purple", lwd = 2)
4 ***Draw a needle graph for the variable “age” with relative
frequencies (proportions) displayed on the vertical axis. Relative
frequencies (proportions) of each age
rel_freq <- prop.table(table(Bweight$age))
ages <- as.numeric(names(rel_freq))
Mean and standard deviation
xbar <- mean(ages)
s <- sd(ages)
xbar; s
## [1] 29
## [1] 9.092121
Method-of-moments estimates for Gamma(r, lambda):
# r / lambda = xbar and r / lambda^2 = s^2
# => lambda_hat = xbar / s^2, r_hat = xbar^2 / s^2
lambda_hat <- xbar / s^2
r_hat <- xbar^2 / s^2
r_hat; lambda_hat
## [1] 10.17339
## [1] 0.3508065
Needle graph with relative frequencies on the vertical axis
plot(ages, as.numeric(rel_freq), type = "h", lwd = 2,
xlab = "Age of mother (years)", ylab = "Relative frequency",
main = "Needle graph of age with fitted gamma density")
#Fitted gamma density
curve(dgamma(x, shape = r_hat, rate = lambda_hat),
add = TRUE, col = "red", lwd = 2)
legend("topright", legend = sprintf("Gamma(r = %.2f, lambda = %.3f)", r_hat, lambda_hat),
col = "red", lwd = 2, bty = "n")
*** Question 5***
Draw the density histogram of the variable “weight”. Add to this graph the probability density of the normal distribution with expectation and standard deviation equal to the (sample) average and the (sample) standard deviation of “weight”. Calculate the skewness and the excess kurtosis of the variable “weight”, and interpret the found values. Present your numerical results in a table, and mention the used formulae for the skewness and the excess kurtosis
w <- Bweight$weight
n <- length(w)
Sample mean and standard deviation
xbar <- mean(w)
s <- sd(w)
Density histogram with the fitted normal density:
hist(w, freq = FALSE, col = "lightgray",
xlab = "Birth weight (grams)", ylab = "Density",
main = "Density histogram of birth weight")
curve(dnorm(x, mean = xbar, sd = s), add = TRUE, col = "red", lwd = 2)
legend("topleft", legend = sprintf("Normal(mean = %.1f, sd = %.1f)", xbar, s),
col = "red", lwd = 2, bty = "n")
The formulas, where mₖ = (1/n) Σ(xᵢ − x̄)ᵏ and s is the sample standard
deviation:
w <- Bweight$weight; n <- length(w); xbar <- mean(w); s <- sd(w)
m2 <- mean((w - xbar)^2); m3 <- mean((w - xbar)^3); m4 <- mean((w - xbar)^4)
g1 <- m3 / m2^1.5; g2 <- m4 / m2^2 - 3 # (a)
b1 <- mean(((w - xbar)/s)^3); b2 <- mean(((w - xbar)/s)^4) - 3 # (b)
G1 <- g1 * sqrt(n*(n-1)) / (n-2) # (c)
G2 <- ((n-1) / ((n-2)*(n-3))) * ((n+1)*g2 + 6)
round(rbind(a = c(g1, g2), b = c(b1, b2), c = c(G1, G2)), 3)
## [,1] [,2]
## a -0.778 2.923
## b -0.777 2.913
## c -0.779 2.941
\[\widehat{\text{weight}} = 3425.14 \;-\; 259.97\,D_1 \;-\; 277.43\,D_2 \;-\; 316.41\,D_3\]
Bweight$smoke <- factor(Bweight$smoke) # treat smoke as categorical
fit <- lm(weight ~ smoke, data = Bweight)
summary(fit)
##
## Call:
## lm(formula = weight ~ smoke, data = Bweight)
##
## Residuals:
## Min 1Q Median 3Q Max
## -2945.14 -306.14 33.86 368.93 1961.86
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 3425.14 18.87 181.489 < 2e-16 ***
## smoke1 -259.97 79.38 -3.275 0.00109 **
## smoke2 -277.43 66.79 -4.154 3.50e-05 ***
## smoke3 -316.41 64.71 -4.890 1.15e-06 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 587.2 on 1196 degrees of freedom
## Multiple R-squared: 0.03661, Adjusted R-squared: 0.03419
## F-statistic: 15.15 on 3 and 1196 DF, p-value: 1.111e-09
coef(fit)
## (Intercept) smoke1 smoke2 smoke3
## 3425.1415 -259.9691 -277.4272 -316.4082
Check: the coefficients reproduce the group means
tapply(Bweight$weight, Bweight$smoke, mean)
## 0 1 2 3
## 3425.142 3165.172 3147.714 3108.733
Overall: All three differences are statistically significant (p ≤ 0.001). The gap grows from category 1 to category 3, so the more the mother smokes, the lower the average birth weight, if the categories are coded that way. Smoking status still explains only about 3.7% of the variation in birth weight, so other factors matter much more. The interpretation assumes smoke = 0 means non-smoker and codes 1–3 mean increasing amounts of smoking. That’s typical, but the file doesn’t label the codes, so check your codebook for the exact category definitions, such as cigarettes per day.