Task 1

packages <- c("tidyverse", "infer", "fst")
new_packages <- packages[!(packages %in% installed.packages()[,"Package"])]
if(length(new_packages)) install.packages(new_packages)

lapply(packages, library, character.only = TRUE)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.2     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ ggplot2   3.4.2     ✔ tibble    3.2.1
## ✔ lubridate 1.9.2     ✔ tidyr     1.3.0
## ✔ purrr     1.0.2     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
## [[1]]
##  [1] "lubridate" "forcats"   "stringr"   "dplyr"     "purrr"     "readr"    
##  [7] "tidyr"     "tibble"    "ggplot2"   "tidyverse" "stats"     "graphics" 
## [13] "grDevices" "utils"     "datasets"  "methods"   "base"     
## 
## [[2]]
##  [1] "infer"     "lubridate" "forcats"   "stringr"   "dplyr"     "purrr"    
##  [7] "readr"     "tidyr"     "tibble"    "ggplot2"   "tidyverse" "stats"    
## [13] "graphics"  "grDevices" "utils"     "datasets"  "methods"   "base"     
## 
## [[3]]
##  [1] "fst"       "infer"     "lubridate" "forcats"   "stringr"   "dplyr"    
##  [7] "purrr"     "readr"     "tidyr"     "tibble"    "ggplot2"   "tidyverse"
## [13] "stats"     "graphics"  "grDevices" "utils"     "datasets"  "methods"  
## [19] "base"
library(fst)
ess <- read_fst("All-ESS-Data.fst")
france_data <- ess %>%
  filter(cntry == "FR")

df <- france_data
library(modelsummary)
df=df %>% mutate(happy1 = ifelse(happy  %in% c(77, 88, 99), NA, happy))%>% mutate(stfedu1 = ifelse(stfedu %in% c(77, 88, 99), NA, stfedu))
ggplot(df, aes(x = happy1)) +
  geom_histogram(nbins=5, fill = "blue", color = "black")+
  labs(title = "Histogram of happy",
       x = "happy",
       y = "Count")
## Warning in geom_histogram(nbins = 5, fill = "blue", color = "black"): Ignoring
## unknown parameters: `nbins`
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## Warning: Removed 26 rows containing non-finite values (`stat_bin()`).

ggplot(df, aes(x = stfedu1)) +
  geom_histogram(nbins=5, fill = "blue", color = "black")+
  labs(title = "Histogram of education",
       x = "education",
       y = "Count")
## Warning in geom_histogram(nbins = 5, fill = "blue", color = "black"): Ignoring
## unknown parameters: `nbins`
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## Warning: Removed 318 rows containing non-finite values (`stat_bin()`).

m1=lm(df$happy1~df$stfedu1)
summary(m1)
## 
## Call:
## lm(formula = df$happy1 ~ df$stfedu1)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -7.9578 -1.0639  0.3401  1.0851  3.5320 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept) 6.467980   0.032814  197.11   <2e-16 ***
## df$stfedu1  0.148986   0.006066   24.56   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 1.766 on 18693 degrees of freedom
##   (343 observations deleted due to missingness)
## Multiple R-squared:  0.03127,    Adjusted R-squared:  0.03121 
## F-statistic: 603.3 on 1 and 18693 DF,  p-value: < 2.2e-16
tab_dat <- df

mytab <- table(df$happy1, df$stfedu1)

rsums <- rowSums(mytab)

csums <- colSums(mytab)

N <- sum(mytab)

ptab <- tcrossprod(rsums/N, csums/N)
cat("Table of Expected Proportions:\n")
## Table of Expected Proportions:
print(ptab)
##               [,1]         [,2]         [,3]         [,4]         [,5]
##  [1,] 0.0001675579 1.138273e-04 0.0003251846 0.0005492742 0.0006669213
##  [2,] 0.0001016644 6.906378e-05 0.0001973030 0.0003332675 0.0004046489
##  [3,] 0.0003407639 2.314916e-04 0.0006613305 0.0011170633 0.0013563230
##  [4,] 0.0006382262 4.335671e-04 0.0012386245 0.0020921793 0.0025402956
##  [5,] 0.0009526327 6.471532e-04 0.0018488023 0.0031228399 0.0037917097
##  [6,] 0.0042699030 2.900679e-03 0.0082867266 0.0139972351 0.0169952520
##  [7,] 0.0034754148 2.360958e-03 0.0067448400 0.0113928113 0.0138329962
##  [8,] 0.0074309114 5.048051e-03 0.0144213888 0.0243593857 0.0295768341
##  [9,] 0.0103735297 7.047063e-03 0.0201322149 0.0340056284 0.0412891705
## [10,] 0.0044468742 3.020901e-03 0.0086301800 0.0145773674 0.0176996408
## [11,] 0.0029990985 2.037382e-03 0.0058204389 0.0098313913 0.0119371413
##               [,6]         [,7]         [,8]         [,9]        [,10]
##  [1,] 0.0009760631 0.0007560478 0.0006717596 0.0003916475 8.097784e-05
##  [2,] 0.0005922181 0.0004587256 0.0004075845 0.0002376288 4.913262e-05
##  [3,] 0.0019850272 0.0015375804 0.0013661627 0.0007964967 1.646853e-04
##  [4,] 0.0037178133 0.0028797776 0.0025587246 0.0014917811 3.084437e-04
##  [5,] 0.0055493025 0.0042984292 0.0038192173 0.0022266703 4.603909e-04
##  [6,] 0.0248731581 0.0192664770 0.0171185471 0.0099804115 2.063570e-03
##  [7,] 0.0202450837 0.0156816211 0.0139333501 0.0081233861 1.679608e-03
##  [8,] 0.0432867527 0.0335294466 0.0297914045 0.0173689083 3.591231e-03
##  [9,] 0.0604281751 0.0468070055 0.0415887101 0.0242469432 5.013347e-03
## [10,] 0.0259040562 0.0200649994 0.0178280460 0.0103940617 2.149097e-03
## [11,] 0.0174704325 0.0135324065 0.0120237414 0.0070100509 1.449412e-03
##              [,11]
##  [1,] 6.137000e-05
##  [2,] 3.723573e-05
##  [3,] 1.248086e-04
##  [4,] 2.337576e-04
##  [5,] 3.489126e-04
##  [6,] 1.563901e-03
##  [7,] 1.272910e-03
##  [8,] 2.721656e-03
##  [9,] 3.799423e-03
## [10,] 1.628718e-03
## [11,] 1.098454e-03
ftab <- N * ptab
cat("Table of Expected Frequencies:\n")
## Table of Expected Frequencies:
print(ftab)
##             [,1]       [,2]       [,3]       [,4]      [,5]       [,6]
##  [1,]   3.132495   2.128002   6.079326  10.268681  12.46809   18.24750
##  [2,]   1.900615   1.291147   3.688580   6.230436   7.56491   11.07152
##  [3,]   6.370580   4.327735  12.363573  20.883498  25.35646   37.11008
##  [4,]  11.931639   8.105536  23.156085  39.113292  47.49083   69.50452
##  [5,]  17.809468  12.098529  34.563359  58.381492  70.88601  103.74421
##  [6,]  79.825836  54.228189 154.920353 261.678310 317.72624  465.00369
##  [7,]  64.972880  44.138112 126.094785 212.988607 258.60786  378.48184
##  [8,] 138.920888  94.373308 269.607863 455.398716 552.93891  809.24584
##  [9,] 193.933137 131.744852 376.371757 635.735223 771.90104 1129.70473
## [10,]  83.134314  56.475742 161.341214 272.523883 330.89478  484.27633
## [11,]  56.068147  38.088847 108.813105 183.797860 223.16486  326.60974
##             [,7]       [,8]       [,9]      [,10]     [,11]
##  [1,]  14.134314  12.558545   7.321851  1.5138807  1.147312
##  [2,]   8.575876   7.619791   4.442471  0.9185344  0.696122
##  [3,]  28.745066  25.540412  14.890505  3.0787911  2.333298
##  [4,]  53.837443  47.835357  27.888847  5.7663546  4.370099
##  [5,]  80.359133  71.400267  41.627601  8.6070072  6.522921
##  [6,] 360.186788 320.031238 186.583792 38.5784434 29.237122
##  [7,] 293.167906 260.483980 151.866702 31.4002675 23.797058
##  [8,] 626.833003 556.950308 324.711741 67.1380583 50.881359
##  [9,] 875.056967 777.500936 453.296603 93.7245253 71.030222
## [10,] 375.115164 333.295320 194.316983 40.1773736 30.448890
## [11,] 252.988339 224.783846 131.052902 27.0967638 20.535598
alpha <- 0.05 # significance level
c_val <- qchisq(alpha, df = 1, lower.tail = FALSE)
cat("Critical Value:", round(c_val, 3), "\n")
## Critical Value: 3.841
# Pearson's chi-squared statistic:
test_stat <- sum((mytab - ftab)^2 / ftab)
cat("Pearson's X^2:", round(test_stat, 4), "\n")
## Pearson's X^2: 1692.941
# p-value:
p_val <- pchisq(test_stat, df = 1, lower.tail = F)
cat("p-value:", round(p_val, 4), "\n")
## p-value: 0
cat("Chi-squared test result:\n")
## Chi-squared test result:
print(chisq.test(mytab, correct = F))
## Warning in chisq.test(mytab, correct = F): Chi-squared approximation may be
## incorrect
## 
##  Pearson's Chi-squared test
## 
## data:  mytab
## X-squared = 1692.9, df = 100, p-value < 2.2e-16

https://ess.sikt.no/en/datafile/f37d014a-6958-42d4-b03b-17c29e481d3d/256?tab=1&elements=[%22f38e3867-0b7a-46de-9105-639b7a20a981/4%22]

df=df%>%
  mutate(
    stfedu = case_when(
      stfedu == 0 ~ "Extremely Bad",
      stfedu %in% c(1,2,3) ~ "Bad",
      stfedu %in% c(4, 5,6) ~ "Good",
      stfedu %in% c(7, 8, 9,10) ~ "Very good",
      stfedu  %in% c(77, 88, 99) ~ NA_character_,
      TRUE ~ as.character(stfedu)
    )
  ) %>% mutate(
     happy = case_when(
      happy == 0 ~ "Extremely Sad",
      happy %in% c(1,2,3) ~ "Sad",
      happy %in% c(4, 5,6) ~ "Happy",
      happy %in% c(7, 8, 9,10) ~ "Very Happy",
      happy %in% c(77, 88, 99) ~ NA_character_,
      TRUE ~ as.character(happy)
    )
  )
df=df%>%
  mutate(
 religious = case_when(
      rlgdgr %in% c(77, 88, 99) ~ NA_real_,
      TRUE ~ rlgdgr))
df=df%>%
  mutate(gen = case_when(
      yrbrn %in% 1900:1945 ~ "1",
      yrbrn %in% 1946:1964 ~ "2",
      yrbrn %in% 1965:1979 ~ "3",
      yrbrn %in% 1980:1996 ~ "4",
      TRUE ~ as.character(yrbrn)
    ),
    gen = factor(gen, levels = c("1", "2", "3", "4"),
                 labels = c("Interwar", "Baby Boomers", "Gen X", "Millennials")))
library(infer)
library(dplyr)
a=df%>% select(happy,stfedu)
test_stat <- a %>%specify(explanatory =stfedu, response = happy) %>% hypothesize(null = "independence") %>%calculate(stat = "Chisq")
## Warning: Removed 343 rows containing missing values.
print(test_stat$stat)
## X-squared 
##  588.0027

The chi square test statistics is 8.176048.

null_distribution <- a %>%
  specify(explanatory = stfedu,
          response = happy) %>%
  hypothesize(null = "independence") %>%
  generate(reps = 1000, type = "permute") %>%
  calculate(stat = "Chisq")
## Warning: Removed 343 rows containing missing values.
p_val <- null_distribution %>% 
  get_pvalue(obs_stat = test_stat, direction = "two-sided") 
## Warning: Please be cautious in reporting a p-value of 0. This result is an
## approximation based on the number of `reps` chosen in the `generate()` step.
## See `?get_p_value()` for more information.
p_val
## # A tibble: 1 × 1
##   p_value
##     <dbl>
## 1       0
null_distribution %>%
  visualize() +
  shade_p_value(obs_stat = test_stat, direction = "two-sided")
## Warning: Chi-Square usually corresponds to right-tailed tests. Proceed with
## caution.

null_distribution
## Response: happy (factor)
## Explanatory: stfedu (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate  stat
##        <int> <dbl>
##  1         1  7.58
##  2         2 15.0 
##  3         3 10.7 
##  4         4  8.31
##  5         5 11.5 
##  6         6  7.68
##  7         7  3.59
##  8         8  8.39
##  9         9  7.18
## 10        10  6.09
## # ℹ 990 more rows
test_stat <-588.0027 
 null_dist=null_distribution
conf_int <- null_dist %>%
  get_confidence_interval(level = 0.95, type = "percentile")

# Visualize the null distribution with manual x-axis limits
null_dist %>%
  visualize(bins = 15, method = "simulation", dens_color = "black") +
  geom_vline(aes(xintercept = test_stat), color = "red", linetype = "dashed", size = 1) +
  shade_p_value(obs_stat = test_stat, direction = "greater") +
  shade_confidence_interval(endpoints = conf_int) +
  coord_cartesian(xlim = c(0, max(null_dist$stat) * 1.1)) + # Set manual x-axis limits
  labs(title = "Simulation-Based Null Distribution",
       x = "F statistic",
       y = "Count")
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
## Warning in min(diff(unique_loc)): no non-missing arguments to min; returning
## Inf

df <- df %>% filter(!is.na(gen))
df <- df %>% filter(!is.na(religious))
df1=df %>%
  mutate(
   gen_num = as.numeric(gen),  
    reli_num = as.numeric(religious),
    
  )
datasummary_skim(df1  %>% dplyr::select(happy1, gen_num, reli_num, stfedu1), output = "flextable")
## Warning: The histogram argument is only supported for (a) output types "default",
##   "html", "kableExtra", or "gt"; (b) writing to file paths with extensions
##   ".html", ".jpg", or ".png"; and (c) Rmarkdown, knitr or Quarto documents
##   compiled to PDF (via kableExtra)  or HTML (via kableExtra or gt). Use
##   `histogram=FALSE` to silence this warning.

Unique (#)

Missing (%)

Mean

SD

Min

Median

Max

happy1

12

0

7.2

1.8

0.0

8.0

10.0

gen_num

4

0

2.4

1.0

1.0

2.0

4.0

reli_num

11

0

4.2

3.2

0.0

5.0

10.0

stfedu1

12

2

5.0

2.1

0.0

5.0

10.0

df$weight <- df$dweight * df$pweight
model1 <- lm(happy1 ~stfedu1 , data = df, weights = weight)
summary(model1)
## 
## Call:
## lm(formula = happy1 ~ stfedu1, data = df, weights = weight)
## 
## Weighted Residuals:
##      Min       1Q   Median       3Q      Max 
## -20.6690  -1.7372   0.2951   1.6002  10.2254 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept) 6.595400   0.032494  202.97   <2e-16 ***
## stfedu1     0.145052   0.006008   24.14   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 2.841 on 18066 degrees of freedom
##   (323 observations deleted due to missingness)
## Multiple R-squared:  0.03126,    Adjusted R-squared:  0.03121 
## F-statistic:   583 on 1 and 18066 DF,  p-value: < 2.2e-16
model2 <- lm(happy1 ~stfedu1+religious, data = df, weights = weight)
summary(model2)
## 
## Call:
## lm(formula = happy1 ~ stfedu1 + religious, data = df, weights = weight)
## 
## Weighted Residuals:
##      Min       1Q   Median       3Q      Max 
## -20.8114  -1.7264   0.3062   1.5813  10.1840 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept) 6.555482   0.035650  183.88  < 2e-16 ***
## stfedu1     0.144041   0.006018   23.93  < 2e-16 ***
## religious   0.010825   0.003980    2.72  0.00654 ** 
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 2.84 on 18065 degrees of freedom
##   (323 observations deleted due to missingness)
## Multiple R-squared:  0.03166,    Adjusted R-squared:  0.03155 
## F-statistic: 295.3 on 2 and 18065 DF,  p-value: < 2.2e-16
model3 <- lm(happy1 ~stfedu1+religious+gen, data = df, weights = weight)
summary(model3)
## 
## Call:
## lm(formula = happy1 ~ stfedu1 + religious + gen, data = df, weights = weight)
## 
## Weighted Residuals:
##      Min       1Q   Median       3Q      Max 
## -21.0901  -1.6994   0.2393   1.6214  10.1863 
## 
## Coefficients:
##                 Estimate Std. Error t value Pr(>|t|)    
## (Intercept)     6.383067   0.046152 138.305  < 2e-16 ***
## stfedu1         0.137853   0.006009  22.942  < 2e-16 ***
## religious       0.016664   0.004001   4.164 3.14e-05 ***
## genBaby Boomers 0.044659   0.037660   1.186    0.236    
## genGen X        0.257666   0.039344   6.549 5.94e-11 ***
## genMillennials  0.453132   0.042052  10.775  < 2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 2.827 on 18062 degrees of freedom
##   (323 observations deleted due to missingness)
## Multiple R-squared:  0.04091,    Adjusted R-squared:  0.04064 
## F-statistic: 154.1 on 5 and 18062 DF,  p-value: < 2.2e-16
model4 <- lm(happy1 ~stfedu1*religious+gen, data = df, weights = weight)
summary(model4)
## 
## Call:
## lm(formula = happy1 ~ stfedu1 * religious + gen, data = df, weights = weight)
## 
## Weighted Residuals:
##      Min       1Q   Median       3Q      Max 
## -21.0054  -1.6923   0.2398   1.6160  10.5957 
## 
## Coefficients:
##                    Estimate Std. Error t value Pr(>|t|)    
## (Intercept)        6.239303   0.058621 106.435  < 2e-16 ***
## stfedu1            0.167447   0.009566  17.504  < 2e-16 ***
## religious          0.050816   0.009477   5.362 8.34e-08 ***
## genBaby Boomers    0.044868   0.037644   1.192    0.233    
## genGen X           0.256626   0.039328   6.525 6.97e-11 ***
## genMillennials     0.451596   0.042037  10.743  < 2e-16 ***
## stfedu1:religious -0.006865   0.001727  -3.975 7.07e-05 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 2.826 on 18061 degrees of freedom
##   (323 observations deleted due to missingness)
## Multiple R-squared:  0.04174,    Adjusted R-squared:  0.04143 
## F-statistic: 131.1 on 6 and 18061 DF,  p-value: < 2.2e-16
library(modelsummary)
modelsummary(
  list(model1, model2, model3,model4),
  fmt = 3,
  estimate  = c( "{estimate} ({std.error}){stars}",
                "{estimate} ({std.error}){stars}",
                "{estimate} ({std.error}){stars}",
                 "{estimate} ({std.error}){stars}"),
  statistic = NULL,
  coef_omit = "Intercept")
 (1)   (2)   (3)   (4)
stfedu1 0.145 (0.006)*** 0.144 (0.006)*** 0.138 (0.006)*** 0.167 (0.010)***
religious 0.011 (0.004)** 0.017 (0.004)*** 0.051 (0.009)***
genBaby Boomers 0.045 (0.038) 0.045 (0.038)
genGen X 0.258 (0.039)*** 0.257 (0.039)***
genMillennials 0.453 (0.042)*** 0.452 (0.042)***
stfedu1 × religious −0.007 (0.002)***
Num.Obs. 18068 18068 18068 18068
R2 0.031 0.032 0.041 0.042
R2 Adj. 0.031 0.032 0.041 0.041
AIC 72864.9 72859.5 72692.1 72678.3
BIC 72888.3 72890.7 72746.7 72740.7
Log.Lik. −36429.449 −36425.750 −36339.043 −36331.143
RMSE 1.77 1.77 1.76 1.76
 models <- list(
   "Model 1" =lm(happy1 ~stfedu1 , data = df, weights = weight),
   "Model 2" =lm(happy1 ~stfedu1+religious, data = df, weights = weight),
   "Model 3" = lm(happy1 ~stfedu1+religious+gen, data = df, weights = weight),
   "Model 4" = lm(happy1 ~stfedu1*religious+gen, data = df, weights = weight))
modelplot(models, coef_omit = 'Interc')

df$year <- NA
replacements <- c(1984, 1989, 1994, 1999, 2005, 2008, 2013, 2018)
for(i in 1:8){
  df$year[df$essround == i] <- replacements[i]
}
safe_avg <- df %>%
  group_by(year) %>%
  summarize(happy11 = mean(happy1, na.rm = TRUE))

plot1<- ggplot(safe_avg, aes(x = year, y =happy11)) +
  geom_point(aes(size =happy11, color =happy11), alpha = 0.7) + 
  geom_line(aes(group = 1), color = "red", linetype = "dashed") +  labs(title = "Happiness Average by Year (France)",x = "Survey Year",
       y = "Happiness Average") +
  theme_minimal() +
  theme(legend.position = "none")

print(plot1)
## Warning: Removed 1 rows containing missing values (`geom_point()`).
## Warning: Removed 1 row containing missing values (`geom_line()`).

par(mfrow = c(2,2)) # plot 2 X 2 matrix, by row

# plot diagnostics plots
plot(model4, pch = 19, col = scales::alpha("grey", .8), cex = .5)

df$year <- NA
replacements <- c(1984, 1989, 1994, 1999, 2005, 2008, 2013, 2018)
for(i in 1:8){
  df$year[df$essround == i] <- replacements[i]
}

safe_avg <- df %>%
  group_by(year) %>%
  summarize(happy11 = mean(happy1, na.rm = TRUE))

plot_zoom_safe <- ggplot(safe_avg, aes(x = year, y = happy11)) +
  geom_point(aes(size = happy11, color = happy11), alpha = 0.7) + 
  geom_line(aes(group = 1), color = "red", linetype = "dashed") +  labs(title = "Happiness Average by Year (France)",
       x = "Survey Year",
       y = "Happiness Average") +
  theme_minimal() +
  theme(legend.position = "none")

print(plot_zoom_safe)
## Warning: Removed 1 rows containing missing values (`geom_point()`).
## Warning: Removed 1 row containing missing values (`geom_line()`).