packages <- c("tidyverse", "modelsummary", "forcats", "RColorBrewer", 
              "fst", "viridis", "knitr", "rmarkdown", "ggridges", "viridis", "questionr", "flextable", "infer") 

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.3     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.0
## ✔ ggplot2   3.4.3     ✔ 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
## Loading required package: viridisLite
## 
## 
## Attaching package: 'flextable'
## 
## 
## The following object is masked from 'package:purrr':
## 
##     compose
## [[1]]
##  [1] "lubridate" "forcats"   "stringr"   "dplyr"     "purrr"     "readr"    
##  [7] "tidyr"     "tibble"    "ggplot2"   "tidyverse" "stats"     "graphics" 
## [13] "grDevices" "utils"     "datasets"  "methods"   "base"     
## 
## [[2]]
##  [1] "modelsummary" "lubridate"    "forcats"      "stringr"      "dplyr"       
##  [6] "purrr"        "readr"        "tidyr"        "tibble"       "ggplot2"     
## [11] "tidyverse"    "stats"        "graphics"     "grDevices"    "utils"       
## [16] "datasets"     "methods"      "base"        
## 
## [[3]]
##  [1] "modelsummary" "lubridate"    "forcats"      "stringr"      "dplyr"       
##  [6] "purrr"        "readr"        "tidyr"        "tibble"       "ggplot2"     
## [11] "tidyverse"    "stats"        "graphics"     "grDevices"    "utils"       
## [16] "datasets"     "methods"      "base"        
## 
## [[4]]
##  [1] "RColorBrewer" "modelsummary" "lubridate"    "forcats"      "stringr"     
##  [6] "dplyr"        "purrr"        "readr"        "tidyr"        "tibble"      
## [11] "ggplot2"      "tidyverse"    "stats"        "graphics"     "grDevices"   
## [16] "utils"        "datasets"     "methods"      "base"        
## 
## [[5]]
##  [1] "fst"          "RColorBrewer" "modelsummary" "lubridate"    "forcats"     
##  [6] "stringr"      "dplyr"        "purrr"        "readr"        "tidyr"       
## [11] "tibble"       "ggplot2"      "tidyverse"    "stats"        "graphics"    
## [16] "grDevices"    "utils"        "datasets"     "methods"      "base"        
## 
## [[6]]
##  [1] "viridis"      "viridisLite"  "fst"          "RColorBrewer" "modelsummary"
##  [6] "lubridate"    "forcats"      "stringr"      "dplyr"        "purrr"       
## [11] "readr"        "tidyr"        "tibble"       "ggplot2"      "tidyverse"   
## [16] "stats"        "graphics"     "grDevices"    "utils"        "datasets"    
## [21] "methods"      "base"        
## 
## [[7]]
##  [1] "knitr"        "viridis"      "viridisLite"  "fst"          "RColorBrewer"
##  [6] "modelsummary" "lubridate"    "forcats"      "stringr"      "dplyr"       
## [11] "purrr"        "readr"        "tidyr"        "tibble"       "ggplot2"     
## [16] "tidyverse"    "stats"        "graphics"     "grDevices"    "utils"       
## [21] "datasets"     "methods"      "base"        
## 
## [[8]]
##  [1] "rmarkdown"    "knitr"        "viridis"      "viridisLite"  "fst"         
##  [6] "RColorBrewer" "modelsummary" "lubridate"    "forcats"      "stringr"     
## [11] "dplyr"        "purrr"        "readr"        "tidyr"        "tibble"      
## [16] "ggplot2"      "tidyverse"    "stats"        "graphics"     "grDevices"   
## [21] "utils"        "datasets"     "methods"      "base"        
## 
## [[9]]
##  [1] "ggridges"     "rmarkdown"    "knitr"        "viridis"      "viridisLite" 
##  [6] "fst"          "RColorBrewer" "modelsummary" "lubridate"    "forcats"     
## [11] "stringr"      "dplyr"        "purrr"        "readr"        "tidyr"       
## [16] "tibble"       "ggplot2"      "tidyverse"    "stats"        "graphics"    
## [21] "grDevices"    "utils"        "datasets"     "methods"      "base"        
## 
## [[10]]
##  [1] "ggridges"     "rmarkdown"    "knitr"        "viridis"      "viridisLite" 
##  [6] "fst"          "RColorBrewer" "modelsummary" "lubridate"    "forcats"     
## [11] "stringr"      "dplyr"        "purrr"        "readr"        "tidyr"       
## [16] "tibble"       "ggplot2"      "tidyverse"    "stats"        "graphics"    
## [21] "grDevices"    "utils"        "datasets"     "methods"      "base"        
## 
## [[11]]
##  [1] "questionr"    "ggridges"     "rmarkdown"    "knitr"        "viridis"     
##  [6] "viridisLite"  "fst"          "RColorBrewer" "modelsummary" "lubridate"   
## [11] "forcats"      "stringr"      "dplyr"        "purrr"        "readr"       
## [16] "tidyr"        "tibble"       "ggplot2"      "tidyverse"    "stats"       
## [21] "graphics"     "grDevices"    "utils"        "datasets"     "methods"     
## [26] "base"        
## 
## [[12]]
##  [1] "flextable"    "questionr"    "ggridges"     "rmarkdown"    "knitr"       
##  [6] "viridis"      "viridisLite"  "fst"          "RColorBrewer" "modelsummary"
## [11] "lubridate"    "forcats"      "stringr"      "dplyr"        "purrr"       
## [16] "readr"        "tidyr"        "tibble"       "ggplot2"      "tidyverse"   
## [21] "stats"        "graphics"     "grDevices"    "utils"        "datasets"    
## [26] "methods"      "base"        
## 
## [[13]]
##  [1] "infer"        "flextable"    "questionr"    "ggridges"     "rmarkdown"   
##  [6] "knitr"        "viridis"      "viridisLite"  "fst"          "RColorBrewer"
## [11] "modelsummary" "lubridate"    "forcats"      "stringr"      "dplyr"       
## [16] "purrr"        "readr"        "tidyr"        "tibble"       "ggplot2"     
## [21] "tidyverse"    "stats"        "graphics"     "grDevices"    "utils"       
## [26] "datasets"     "methods"      "base"
setwd("~/Desktop/SOC202")
ess <- read_fst("~/Desktop/SOC202/All-ESS-Data.fst")
france_data <- ess %>%
  filter(cntry == "FR")
write_fst(france_data, "~/Desktop/SOC202/france_data.fst") 
rm(list=ls()); gc()
##           used (Mb) gc trigger   (Mb) limit (Mb)   max used    (Mb)
## Ncells 1264977 67.6    2135114  114.1         NA    2135114   114.1
## Vcells 2158727 16.5 1257028829 9590.4      16384 1356024634 10345.7
df <- read_fst("~/Desktop/SOC202/france_data.fst") 
df$year <- NA
replacements <- c(2002, 2004, 2006, 2008, 2010, 2012, 2014, 2016, 2018, 2020)
for(i in 1:10){
  df$year[df$essround == i] <- replacements[i]
}

france_data <- df
france_data_table_subset <- france_data %>%
  mutate(
    happy = ifelse(happy == 2, 0, ifelse(happy %in% c(66,77, 88, 99), NA, happy)), 
    edulvla = ifelse(edulvla %in% c(55, 77, 88, 99), NA, edulvla), 
    gndr = ifelse(gndr %in% c(77, 88, 99), NA, gndr) 
  )
summary_table <- datasummary_skim(france_data_table_subset %>% select (happy, edulvla, gndr), 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.
summary_table

Unique (#)

Missing (%)

Mean

SD

Min

Median

Max

happy

11

0

7.2

1.9

0.0

8.0

10.0

edulvla

6

61

3.0

1.4

1.0

3.0

5.0

gndr

2

0

1.5

0.5

1.0

2.0

2.0

france_data_v2 <- france_data_table_subset %>%
  rename(
    `How Happy Are You` = happy,
    `Level of Education` = edulvla,
    `Gender` = gndr
    
  )
summary_table_v2 <- datasummary_skim(france_data_v2 %>% select(`How Happy Are You`,`Level of Education`,`Gender`), 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.
summary_table_v2

Unique (#)

Missing (%)

Mean

SD

Min

Median

Max

How Happy Are You

11

0

7.2

1.9

0.0

8.0

10.0

Level of Education

6

61

3.0

1.4

1.0

3.0

5.0

Gender

2

0

1.5

0.5

1.0

2.0

2.0

ess <- read_fst("~/Desktop/SOC202/All-ESS-Data.fst")
france_data <- ess %>%
  filter(cntry == "FR") %>%
  
  mutate(
    happy = case_when(
      happy %in% c(66, 77, 88, 99) ~ NA_real_,  
      TRUE ~ as.numeric(happy)  
    ),
        gndr = ifelse(gndr %in% c(77, 88, 99), NA, gndr),
    
    edulvla = case_when(
      essround < 5 & edulvla == 55 ~ NA_real_,
      TRUE ~ edulvla
    ),
    
    edulvlb = case_when(
      essround >= 5 & edulvlb == 5555 ~ NA_real_,
      TRUE ~ edulvlb
    ),
 
    educ_level = case_when(
      essround < 5 & edulvla == 5 ~ "BA",
      essround >= 5 & edulvlb > 600 ~ "BA",
      TRUE ~ "No BA"
    ),
 
    gndr = case_when(
      gndr == 1 ~ "Male",
      gndr == 2 ~ "Female",
      gndr == 9 ~ NA_character_,
      TRUE ~ as.character(gndr)
    )
  )
unique(france_data$gndr)
## [1] "Female" "Male"
unique(france_data$happy)
##  [1] 10  3  6  5  8  7  9  4  2  0  1 NA
france_data <- france_data %>% filter(!is.na(happy))
france_data <- france_data %>% filter(!is.nan(happy))
france_data <- france_data %>% filter(!is.infinite(happy))
france_data <- france_data %>% filter(!is.na(gndr))
france_data <- france_data %>% filter(!is.na(educ_level))

unique(france_data$happy)
##  [1] 10  3  6  5  8  7  9  4  2  0  1
table(france_data$happy)
## 
##    0    1    2    3    4    5    6    7    8    9   10 
##   90   57  185  346  514 2349 1869 4003 5591 2386 1622
tab_dat <- france_data

mytab <- table(tab_dat$happy, tab_dat$educ_level)

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]
##  [1,] 0.0010534888 0.003680364
##  [2,] 0.0006672096 0.002330897
##  [3,] 0.0021655048 0.007565192
##  [4,] 0.0040500792 0.014148953
##  [5,] 0.0060165916 0.021018965
##  [6,] 0.0274960577 0.096057487
##  [7,] 0.0218774508 0.076428882
##  [8,] 0.0468568408 0.163694390
##  [9,] 0.0654450654 0.228632359
## [10,] 0.0279291587 0.097570526
## [11,] 0.0189862093 0.066328329
ftab <- N * ptab
cat("Table of Expected Frequencies:\n")
## Table of Expected Frequencies:
print(ftab)
##             [,1]       [,2]
##  [1,]   20.02893   69.97107
##  [2,]   12.68499   44.31501
##  [3,]   41.17058  143.82942
##  [4,]   77.00011  268.99989
##  [5,]  114.38744  399.61256
##  [6,]  522.75505 1826.24495
##  [7,]  415.93409 1453.06591
##  [8,]  890.84226 3112.15774
##  [9,] 1244.24158 4346.75842
## [10,]  530.98916 1855.01084
## [11,]  360.96581 1261.03419
alpha <- 0.05 
c_val <- qchisq(alpha, df = 1, lower.tail = FALSE)
cat("Critical Value:", round(c_val, 3), "\n")
## Critical Value: 3.841
test_stat <- sum((mytab - ftab)^2 / ftab)
cat("Pearson's X^2:", round(test_stat, 4), "\n")
## Pearson's X^2: 386.8661
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))
## 
##  Pearson's Chi-squared test
## 
## data:  mytab
## X-squared = 386.87, df = 10, p-value < 2.2e-16
test_stat <- france_data %>%
  specify(explanatory = educ_level, 
          response = happy) %>% 
  hypothesize(null = "independence") %>%
  calculate(stat = "t") 
## Warning: The statistic is based on a difference or ratio; by default, for
## difference-based statistics, the explanatory variable is subtracted in the
## order "BA" - "No BA", or divided in the order "BA" / "No BA" for ratio-based
## statistics. To specify this order yourself, supply `order = c("BA", "No BA")`
## to the calculate() function.
print(test_stat$stat)
##        t 
## 15.52386
null_distribution <- france_data %>%
  specify(explanatory = educ_level,
          response = happy) %>%
  hypothesize(null = "independence") %>%
  generate(reps = 1000, type = "permute") %>% 
  calculate(stat = "t")
## Warning: The statistic is based on a difference or ratio; by default, for
## difference-based statistics, the explanatory variable is subtracted in the
## order "BA" - "No BA", or divided in the order "BA" / "No BA" for ratio-based
## statistics. To specify this order yourself, supply `order = c("BA", "No BA")`
## to the calculate() function.
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")

null_distribution
## Response: happy (numeric)
## Explanatory: educ_level (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate   stat
##        <int>  <dbl>
##  1         1  0.262
##  2         2  0.532
##  3         3  0.203
##  4         4  0.555
##  5         5 -2.11 
##  6         6  1.27 
##  7         7 -1.19 
##  8         8  0.114
##  9         9 -1.27 
## 10        10 -0.228
## # ℹ 990 more rows
conf_int <- null_distribution %>%
  get_confidence_interval(level = 0.95, type = "percentile")


null_distribution %>%
  visualize() +
  shade_p_value(obs_stat = test_stat, direction = "two-sided") +
  shade_confidence_interval(endpoints = conf_int)

null_distribution
## Response: happy (numeric)
## Explanatory: educ_level (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate   stat
##        <int>  <dbl>
##  1         1  0.262
##  2         2  0.532
##  3         3  0.203
##  4         4  0.555
##  5         5 -2.11 
##  6         6  1.27 
##  7         7 -1.19 
##  8         8  0.114
##  9         9 -1.27 
## 10        10 -0.228
## # ℹ 990 more rows
france_data$weight <- france_data$dweight * france_data$pweight
model1 <- lm(happy ~ educ_level, data = france_data, weights = weight)
model2 <- lm(happy ~ educ_level + gndr, data = france_data, weights = weight)
model3 <- lm(happy ~ educ_level + gndr*educ_level, data = france_data, weights = weight)
modelsummary(
  list(model1, model2, model3),
  fmt = 1,
  estimate  = c( "{estimate} ({std.error}){stars}",
                "{estimate} ({std.error}){stars}",
                "{estimate} ({std.error}){stars}"),
  statistic = NULL,
  coef_omit = "Intercept")
 (1)   (2)   (3)
educ_levelNo BA −0.4 (0.0)*** −0.4 (0.0)*** −0.4 (0.0)***
gndrMale 0.0 (0.0) −0.1 (0.1)*
educ_levelNo BA × gndrMale 0.1 (0.1)+
Num.Obs. 19012 19012 19012
R2 0.007 0.007 0.008
R2 Adj. 0.007 0.007 0.007
AIC 77125.7 77127.1 77125.6
BIC 77149.3 77158.5 77164.8
Log.Lik. −38559.859 −38559.552 −38557.780
RMSE 1.79 1.79 1.79
modelsummary(
  list(model1, model2, model3),
  fmt = 1,
  estimate  = c( "{estimate} ({std.error}){stars}",
                "{estimate} ({std.error}){stars}",
                "{estimate} ({std.error}){stars}"),
  statistic = NULL,
  coef_rename = c ("happy" = "Happiness", "edulblv" = "Education Level", "gndr" = "Gender"),
  title = 'Regression Models Predicting Individual Happiness on the Level of Educational Attainment and Gender')
Regression Models Predicting Individual Happiness on the Level of Educational Attainment and Gender
 (1)   (2)   (3)
(Intercept) 7.6 (0.0)*** 7.6 (0.0)*** 7.7 (0.0)***
educ_levelNo BA −0.4 (0.0)*** −0.4 (0.0)*** −0.4 (0.0)***
gndrMale 0.0 (0.0) −0.1 (0.1)*
educ_levelNo BA:GenderMale 0.1 (0.1)+
Num.Obs. 19012 19012 19012
R2 0.007 0.007 0.008
R2 Adj. 0.007 0.007 0.007
AIC 77125.7 77127.1 77125.6
BIC 77149.3 77158.5 77164.8
Log.Lik. −38559.859 −38559.552 −38557.780
RMSE 1.79 1.79 1.79
df <- france_data %>%
  filter(!is.na(educ_level) & !is.na(happy))

df <- df %>%
  mutate(happy = case_when(
    happy == 1 ~ "Yes",
    happy == 10 ~ "No",
    happy %in% c(0, 2, 3:9, 66, 77, 88, 99) ~ NA_character_,
    TRUE ~ as.character(happy)  
  ))

table(df$happy)
## 
##   No  Yes 
## 1622   57
table(df$happy, df$educ_level) %>%
  cprop() %>%
  as.data.frame() %>%
  filter(Var1 != "Total",
         Var2 != "All") %>%
  ggplot(aes(x=Var1, y=Freq, fill=Var2)) +
  geom_col(position = "dodge") +
  labs(title="Individual Happiness in France",
       y = "Conditional Percentage",
       x = "Feeling Happy",
       fill = "At least BA vs. No BA")