rm(list=ls()); gc()
##          used (Mb) gc trigger (Mb) limit (Mb) max used (Mb)
## Ncells 524893 28.1    1164975 62.3         NA   669437 35.8
## Vcells 966981  7.4    8388608 64.0      16384  1851813 14.2
packages <- c("tidyverse", "infer", "fst", "modelsummary", "effects", "survey", "MASS", "kableExtra", "flextable", "equatiomatic") # add any you need here

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.4     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ 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: carData
## 
## lattice theme set by effectsTheme()
## See ?effectsTheme for details.
## 
## Loading required package: grid
## 
## Loading required package: Matrix
## 
## 
## Attaching package: 'Matrix'
## 
## 
## The following objects are masked from 'package:tidyr':
## 
##     expand, pack, unpack
## 
## 
## Loading required package: survival
## 
## 
## Attaching package: 'survey'
## 
## 
## The following object is masked from 'package:graphics':
## 
##     dotchart
## 
## 
## 
## Attaching package: 'MASS'
## 
## 
## The following object is masked from 'package:dplyr':
## 
##     select
## 
## 
## 
## Attaching package: 'kableExtra'
## 
## 
## The following object is masked from 'package:dplyr':
## 
##     group_rows
## 
## 
## 
## Attaching package: 'flextable'
## 
## 
## The following objects are masked from 'package:kableExtra':
## 
##     as_image, footnote
## 
## 
## 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] "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"     
## 
## [[4]]
##  [1] "modelsummary" "fst"          "infer"        "lubridate"    "forcats"     
##  [6] "stringr"      "dplyr"        "purrr"        "readr"        "tidyr"       
## [11] "tibble"       "ggplot2"      "tidyverse"    "stats"        "graphics"    
## [16] "grDevices"    "utils"        "datasets"     "methods"      "base"        
## 
## [[5]]
##  [1] "effects"      "carData"      "modelsummary" "fst"          "infer"       
##  [6] "lubridate"    "forcats"      "stringr"      "dplyr"        "purrr"       
## [11] "readr"        "tidyr"        "tibble"       "ggplot2"      "tidyverse"   
## [16] "stats"        "graphics"     "grDevices"    "utils"        "datasets"    
## [21] "methods"      "base"        
## 
## [[6]]
##  [1] "survey"       "survival"     "Matrix"       "grid"         "effects"     
##  [6] "carData"      "modelsummary" "fst"          "infer"        "lubridate"   
## [11] "forcats"      "stringr"      "dplyr"        "purrr"        "readr"       
## [16] "tidyr"        "tibble"       "ggplot2"      "tidyverse"    "stats"       
## [21] "graphics"     "grDevices"    "utils"        "datasets"     "methods"     
## [26] "base"        
## 
## [[7]]
##  [1] "MASS"         "survey"       "survival"     "Matrix"       "grid"        
##  [6] "effects"      "carData"      "modelsummary" "fst"          "infer"       
## [11] "lubridate"    "forcats"      "stringr"      "dplyr"        "purrr"       
## [16] "readr"        "tidyr"        "tibble"       "ggplot2"      "tidyverse"   
## [21] "stats"        "graphics"     "grDevices"    "utils"        "datasets"    
## [26] "methods"      "base"        
## 
## [[8]]
##  [1] "kableExtra"   "MASS"         "survey"       "survival"     "Matrix"      
##  [6] "grid"         "effects"      "carData"      "modelsummary" "fst"         
## [11] "infer"        "lubridate"    "forcats"      "stringr"      "dplyr"       
## [16] "purrr"        "readr"        "tidyr"        "tibble"       "ggplot2"     
## [21] "tidyverse"    "stats"        "graphics"     "grDevices"    "utils"       
## [26] "datasets"     "methods"      "base"        
## 
## [[9]]
##  [1] "flextable"    "kableExtra"   "MASS"         "survey"       "survival"    
##  [6] "Matrix"       "grid"         "effects"      "carData"      "modelsummary"
## [11] "fst"          "infer"        "lubridate"    "forcats"      "stringr"     
## [16] "dplyr"        "purrr"        "readr"        "tidyr"        "tibble"      
## [21] "ggplot2"      "tidyverse"    "stats"        "graphics"     "grDevices"   
## [26] "utils"        "datasets"     "methods"      "base"        
## 
## [[10]]
##  [1] "equatiomatic" "flextable"    "kableExtra"   "MASS"         "survey"      
##  [6] "survival"     "Matrix"       "grid"         "effects"      "carData"     
## [11] "modelsummary" "fst"          "infer"        "lubridate"    "forcats"     
## [16] "stringr"      "dplyr"        "purrr"        "readr"        "tidyr"       
## [21] "tibble"       "ggplot2"      "tidyverse"    "stats"        "graphics"    
## [26] "grDevices"    "utils"        "datasets"     "methods"      "base"
tinytex::install_tinytex(force = TRUE)
## The directory /usr/local/bin is not writable. I recommend that you make it writable. See https://github.com/rstudio/tinytex/issues/24 for more info.
## tlmgr install colortbl multirow wrapfig
ess <- read_fst("All-ESS-Data.fst")
monternegro_data <- ess %>%
  filter(cntry == "ME") %>%
  mutate(

    happy = ifelse(happy %in% c(77, 88, 99), NA, happy),
    #cleaning our main predictor education level 
     edulvla = edulvla %>%
    na_if(55) %>%
    na_if(77) %>%
    na_if(88) %>%
    na_if(99),

edulvlb = edulvlb %>%
    na_if(5555) %>%
    na_if(7777) %>%
    na_if(8888) %>%
    na_if(9999), 

#changed BA and No BA to a numeric for later coding 
educ.ba = case_when(
    essround < 5 & edulvla == 5 ~ 1,
    essround >= 5 & edulvlb > 600 ~ 1,
    TRUE ~ 0
),

     imprich = ifelse(imprich %in% c(77, 88, 99), NA, imprich)
  )

# not a bad practice to create a duplicate in case you need to backtrack or use for different purposes
df <- monternegro_data
monternegro_data <- monternegro_data %>% filter(!is.na(happy))
monternegro_data <- monternegro_data %>% filter(!is.na(educ.ba))
monternegro_data <- monternegro_data %>% filter(!is.na(imprich))

table(monternegro_data$happy)
## 
##   0   1   2   3   4   5   6   7   8   9  10 
##  11   8  23  46  79 221 223 478 547 274 560
table(monternegro_data$educ.ba)
## 
##    0    1 
## 2081  389
table(monternegro_data$imprich)
## 
##   1   2   3   4   5   6   7   8 
## 141 339 572 491 551 340  17  19
rm(ess)
d <- df %>%
  # Convert factors/characters to numeric
  mutate(
    happy = as.numeric(happy),
    imprich = as.numeric(imprich),
    educ_ba_num = as.numeric(educ.ba)
  )
table1 <- datasummary_skim(d  %>% dplyr::select(happy, imprich, educ_ba_num), 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.
table1

Unique (#)

Missing (%)

Mean

SD

Min

Median

Max

happy

12

0

7.6

2.0

0.0

8.0

10.0

imprich

8

0

3.9

1.5

1.0

4.0

8.0

educ_ba_num

2

0

0.2

0.4

0.0

0.0

1.0

d <- d %>%
  rename(
    `Happiness` = happy,
    `important to be rich` = imprich,
    `Educational Attainment` = educ_ba_num
  )
  
  table1_v2 <- datasummary_skim(d %>% dplyr::select(`Happiness`,`important to be rich`, `Educational Attainment`), title = "Descriptive Statistics of Variables", 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.
table1_v2
Descriptive Statistics of Variables

Unique (#)

Missing (%)

Mean

SD

Min

Median

Max

Happiness

12

0

7.6

2.0

0.0

8.0

10.0

important to be rich

8

0

3.9

1.5

1.0

4.0

8.0

Educational Attainment

2

0

0.2

0.4

0.0

0.0

1.0

#saving table 1 as a pdf
flextable::save_as_docx(table1_v2, path = "summary_table1_v2.docx", 
                       width = 7.0, height = 7.0) 

set_flextable_defaults(fonts_ignore=TRUE)
print(table1_v2, preview = "pdf")
## a flextable object.
## col_keys: ` `, `Unique (#)`, `Missing (%)`, `Mean`, `SD`, `Min`, `Median`, `Max` 
## header has 1 row(s) 
## body has 3 row(s) 
## original dataset sample: 
##                          Unique (#) Missing (%) Mean  SD Min Median  Max
## 1              Happiness         12           0  7.6 2.0 0.0    8.0 10.0
## 2   important to be rich          8           0  3.9 1.5 1.0    4.0  8.0
## 3 Educational Attainment          2           0  0.2 0.4 0.0    0.0  1.0
df <- monternegro_data %>%
  filter(cntry == "ME") %>%
  mutate(
    happy = ifelse(happy %in% c(77, 88, 99), NA, happy),
     edulvla = edulvla %>%
    na_if(55) %>%
    na_if(77) %>%
    na_if(88) %>%
    na_if(99),

edulvlb = edulvlb %>%
    na_if(5555) %>%
    na_if(7777) %>%
    na_if(8888) %>%
    na_if(9999), 
educ.ba = case_when(
    essround < 5 & edulvla == 5 ~ 'BA',
    essround >= 5 & edulvlb > 600 ~ 'BA',
    TRUE ~ 'No BA'
),
     imprich = ifelse(imprich %in% c(77, 88, 99), NA, imprich)
  )
test_stat <- df %>%
  specify(explanatory = educ.ba, # change variable name for explanatory variable
          response = happy) %>% # change variable name for outcome of interest
  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 
## 3.782592
null_dist <- df %>%
  specify(explanatory = educ.ba,
          response = happy) %>%
  hypothesize(null = "independence") %>%
  generate(reps = 1000, type = "permute") %>% # only line we are adding, use reps = 1000 as standard
  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.
null_dist
## Response: happy (numeric)
## Explanatory: educ.ba (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate    stat
##        <int>   <dbl>
##  1         1 -1.02  
##  2         2 -0.660 
##  3         3  0.212 
##  4         4 -0.505 
##  5         5  0.184 
##  6         6  2.09  
##  7         7 -1.34  
##  8         8  0.0217
##  9         9  1.28  
## 10        10  0.799 
## # ℹ 990 more rows
p_val <- null_dist %>% 
  get_pvalue(obs_stat = test_stat, direction = "two-sided") 
p_val
## # A tibble: 1 × 1
##   p_value
##     <dbl>
## 1   0.004
null_dist %>%
  visualize() +
  shade_p_value(obs_stat = test_stat, direction = "two-sided")

null_dist
## Response: happy (numeric)
## Explanatory: educ.ba (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate    stat
##        <int>   <dbl>
##  1         1 -1.02  
##  2         2 -0.660 
##  3         3  0.212 
##  4         4 -0.505 
##  5         5  0.184 
##  6         6  2.09  
##  7         7 -1.34  
##  8         8  0.0217
##  9         9  1.28  
## 10        10  0.799 
## # ℹ 990 more rows
conf_int <- null_dist %>%
  get_confidence_interval(level = 0.95, type = "percentile")


null_dist %>%
  visualize() +
  shade_p_value(obs_stat = test_stat, direction = "two-sided") +
  shade_confidence_interval(endpoints = conf_int)+
  labs(title = "Figure 1. Simulation-Based Null Distribution",
       x = "T statistic",
       y = "Count")

null_dist
## Response: happy (numeric)
## Explanatory: educ.ba (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate    stat
##        <int>   <dbl>
##  1         1 -1.02  
##  2         2 -0.660 
##  3         3  0.212 
##  4         4 -0.505 
##  5         5  0.184 
##  6         6  2.09  
##  7         7 -1.34  
##  8         8  0.0217
##  9         9  1.28  
## 10        10  0.799 
## # ℹ 990 more rows
df$weight <- df$dweight * df$pweight
model1 <- lm(happy ~ educ.ba, data = df, weights = weight)
model2 <- lm(happy ~ educ.ba + imprich, data = df, weights = weight)
model3 <- lm(happy ~ educ.ba + imprich*educ.ba, data = df, 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.baNo BA −0.4 (0.1)*** −0.4 (0.1)*** −0.3 (0.3)
imprich −0.1 (0.0)* −0.1 (0.1)
educ.baNo BA × imprich 0.0 (0.1)
Num.Obs. 2470 2470 2470
R2 0.005 0.008 0.008
R2 Adj. 0.005 0.007 0.007
AIC 10728.0 10723.6 10725.5
BIC 10745.4 10746.8 10754.6
Log.Lik. −5361.001 −5357.788 −5357.752
RMSE 1.99 1.98 1.98
df <- monternegro_data %>%
  mutate( 
    happy = ifelse(happy %in% c(77, 88, 99), NA, happy),
    #cleaning our main predictor education level 
     edulvla = edulvla %>%
    na_if(55) %>%
    na_if(77) %>%
    na_if(88) %>%
    na_if(99),

edulvlb = edulvlb %>%
    na_if(5555) %>%
    na_if(7777) %>%
    na_if(8888) %>%
    na_if(9999), 

educ.ba = case_when(
    essround < 5 & edulvla == 5 ~ 'BA',
    essround >= 5 & edulvlb > 600 ~ 'BA',
    TRUE ~ 'No BA'
)
)

figure2plot <- ggplot(df, aes(x = reorder(educ.ba, -happy, FUN=median), y = happy, fill = educ.ba)) +
  geom_boxplot() +
  theme_minimal() + 
  theme(legend.position = "none") + 
  labs(title = "Boxplot Comparison for Happiness and Educational Attainment (Monternegro)", 
       x = "Educational Attainment", 
       y = " Happiness Scale (0-10)")

figure2plot

ggsave(filename = "figure2plot.pdf", plot = figure2plot, device = "pdf", width = 8, height = 6)