packages <- c("tidyverse", "infer", "fst", "modelsummary", "broom", "remotes", "effects", "packrat", "rsconnect")

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: carData
## 
## lattice theme set by effectsTheme()
## See ?effectsTheme for details.
## 
## 
## Attaching package: 'packrat'
## 
## 
## The following object is masked from 'package:remotes':
## 
##     install_local
## [[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] "broom"        "modelsummary" "fst"          "infer"        "lubridate"   
##  [6] "forcats"      "stringr"      "dplyr"        "purrr"        "readr"       
## [11] "tidyr"        "tibble"       "ggplot2"      "tidyverse"    "stats"       
## [16] "graphics"     "grDevices"    "utils"        "datasets"     "methods"     
## [21] "base"        
## 
## [[6]]
##  [1] "remotes"      "broom"        "modelsummary" "fst"          "infer"       
##  [6] "lubridate"    "forcats"      "stringr"      "dplyr"        "purrr"       
## [11] "readr"        "tidyr"        "tibble"       "ggplot2"      "tidyverse"   
## [16] "stats"        "graphics"     "grDevices"    "utils"        "datasets"    
## [21] "methods"      "base"        
## 
## [[7]]
##  [1] "effects"      "carData"      "remotes"      "broom"        "modelsummary"
##  [6] "fst"          "infer"        "lubridate"    "forcats"      "stringr"     
## [11] "dplyr"        "purrr"        "readr"        "tidyr"        "tibble"      
## [16] "ggplot2"      "tidyverse"    "stats"        "graphics"     "grDevices"   
## [21] "utils"        "datasets"     "methods"      "base"        
## 
## [[8]]
##  [1] "packrat"      "effects"      "carData"      "remotes"      "broom"       
##  [6] "modelsummary" "fst"          "infer"        "lubridate"    "forcats"     
## [11] "stringr"      "dplyr"        "purrr"        "readr"        "tidyr"       
## [16] "tibble"       "ggplot2"      "tidyverse"    "stats"        "graphics"    
## [21] "grDevices"    "utils"        "datasets"     "methods"      "base"        
## 
## [[9]]
##  [1] "rsconnect"    "packrat"      "effects"      "carData"      "remotes"     
##  [6] "broom"        "modelsummary" "fst"          "infer"        "lubridate"   
## [11] "forcats"      "stringr"      "dplyr"        "purrr"        "readr"       
## [16] "tidyr"        "tibble"       "ggplot2"      "tidyverse"    "stats"       
## [21] "graphics"     "grDevices"    "utils"        "datasets"     "methods"     
## [26] "base"
setwd("~/Downloads/SOC 202 RSCRIPT/")

library(fst)

ess <- read_fst("All-ESS-Data.fst")

Summary Statistics

# Setting up environment and read in the ESS data
france_data <- ess %>%
  # Filtering ESS data for France only, selecting our variables: "happy" (how happy are you), "imprich" (importance of being rich), "gndr" (gender)
  filter(cntry == "FR") %>%
  mutate(happy = ifelse(happy %in% c(77, 88, 99), NA, happy),
         imprich = ifelse(imprich %in% c(7, 8, 9), NA, imprich),
         gndr = ifelse(gndr %in% c(9), NA, gndr)
         ) %>%
  select(happy, imprich, gndr)

# To ensure that data is cleaned, we used the below code "unique(france_data$xxxx)" and "filter(!is.na())" to remove any NA values
unique(france_data$happy)
##  [1] 10  3  6  5  8  7  9  4  2  0  1 NA
# Filter out NAs for "happy", produce a table
france_data <- france_data %>% filter(!is.na(happy))
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
unique(france_data$imprich)
## [1]  5  4  6 NA  2  3  1
# Filter out NAs for "imprich", produce a table 
france_data <- france_data %>% filter(!is.na(imprich))
table(france_data$imprich)
## 
##    1    2    3    4    5    6 
##  367  683 1084 2806 8644 5093
unique(france_data$gndr)
## [1] 2 1
# Filter out NAs for "gndr", produce a table 
france_data <- france_data %>% filter(!is.na(gndr))
table(france_data$gndr)
## 
##     1     2 
##  8659 10018
# Generating data summary table for variables "happy", "imprich" and "gndr" in France
datasummary_skim(france_data, title = "Table 1: Descriptive Statistics of main variables")
Table 1: Descriptive Statistics of main variables
Unique (#) Missing (%) Mean SD Min Median Max
happy 11 0 7.2 1.8 0.0 8.0 10.0
imprich 6 0 4.8 1.1 1.0 5.0 6.0
gndr 2 0 1.5 0.5 1.0 2.0 2.0
# Recode "happy", "imprich" and "gndr" to remove NA variables
france_data_table_subset <- france_data %>%
 mutate(
    happy = ifelse(happy %in% c(77, 88, 99), NA, happy),
    imprich = ifelse(imprich %in% c(7, 8, 9), NA, imprich),
    gndr = ifelse(gndr %in% c(9), NA, gndr),
  )

# Generating data summary table with the variables "happy", "imprich" and "gndr" from France data in different format. We ended up using the first summary table as it depicted simplified distribution graphs.
summary_table <- datasummary_skim(france_data_table_subset %>% select(happy, imprich, gndr), output = "flextable", title = "Table 1: Descriptive Statistics of main variables")
## 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
Table 1: Descriptive Statistics of main variables

Unique (#)

Missing (%)

Mean

SD

Min

Median

Max

happy

11

0

7.2

1.8

0.0

8.0

10.0

imprich

6

0

4.8

1.1

1.0

5.0

6.0

gndr

2

0

1.5

0.5

1.0

2.0

2.0

Null Distribution

france_data <- france_data %>%
  # Recode "happy" 0 to 10 question, leaving it a numerical variable
  mutate(happy = case_when(
      happy %in% c(77, 88, 99) ~ NA_real_,
      TRUE ~ happy)) %>%
  # Recode "imprich", making it a categorical variable with two categories and naming them "Important" and "Not Important" for clarity
  mutate(imprich = case_when(
      imprich %in% c(1, 2, 3, 4) ~ "Important",
      imprich %in% c(5, 6) ~ "Not Important",
      imprich %in% c(7, 8, 9) ~ NA_character_,
      TRUE ~ as.character(imprich))) %>%
  mutate(gndr = case_when(
    gndr == 1 ~ "Male",
    gndr == 2 ~ "Female",
    gndr == 9 ~ NA_character_,
    TRUE ~ as.character(gndr)
  ))

# We used a t test for hypothesis testing as our response is one numeric variable and our explanatory is one categorical variable with two categories ("Important" and "Not Important")
test_stat <- france_data %>%
  specify(explanatory = imprich, 
          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 "Important" - "Not Important", or divided in the order "Important" / "Not
## Important" for ratio-based statistics. To specify this order yourself, supply
## `order = c("Important", "Not Important")` to the calculate() function.
print(test_stat$stat)
##         t 
## -1.454553
# Stimulate the null distribution 
null_distribution <- france_data %>%
  specify(explanatory = imprich,
          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 "Important" - "Not Important", or divided in the order "Important" / "Not
## Important" for ratio-based statistics. To specify this order yourself, supply
## `order = c("Important", "Not Important")` to the calculate() function.
# Stimulate the P-value
p_val <- null_distribution %>%
  get_pvalue(obs_stat = test_stat, direction = "two-sided")

p_val
## # A tibble: 1 × 1
##   p_value
##     <dbl>
## 1   0.142
# Visualize the null distribution
null_distribution %>%
  visualize() +
  shade_p_value(obs_stat = test_stat, direction = "two-sided") +
  ggtitle("Figure 1: Simulation-Based Null Distribution")

null_distribution
## Response: happy (numeric)
## Explanatory: imprich (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate   stat
##        <int>  <dbl>
##  1         1  0.350
##  2         2 -0.892
##  3         3 -0.309
##  4         4  0.676
##  5         5 -0.503
##  6         6 -0.723
##  7         7 -0.454
##  8         8 -0.402
##  9         9  1.45 
## 10        10 -0.734
## # ℹ 990 more rows
# Visualizing the null distribution with confidence interval
conf_int <- null_distribution %>%
  get_confidence_interval(level = 0.95, type = "percentile")

null_distribution %>%
  visualize() +
  shade_p_value(obs_stat = test_stat, direction = "greater") +
  shade_confidence_interval(endpoints = conf_int) +
  ggtitle("Figure 1: Simulation-Based Null Distribution")

null_distribution
## Response: happy (numeric)
## Explanatory: imprich (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate   stat
##        <int>  <dbl>
##  1         1  0.350
##  2         2 -0.892
##  3         3 -0.309
##  4         4  0.676
##  5         5 -0.503
##  6         6 -0.723
##  7         7 -0.454
##  8         8 -0.402
##  9         9  1.45 
## 10        10 -0.734
## # ℹ 990 more rows

Regression

france_data <- france_data %>%
  # Recode "happy" to 0 to 10 question
  mutate(happy = case_when(
      happy %in% c(77, 88, 99) ~ NA_real_,
      TRUE ~ happy)) %>%
  # Recode "imprich" with categories "Important" and "Not Important"
  mutate(imprich = case_when(
      imprich %in% c(1, 2, 3, 4) ~ "Important",
      imprich %in% c(5, 6) ~ "Not Important",
      imprich %in% c(7, 8, 9) ~ NA_character_,
      TRUE ~ as.character(imprich))) %>%
  # Recode "gndr"
  mutate(gndr = case_when(
    gndr == 1 ~ "Male",
    gndr == 2 ~ "Female",
    gndr == 9 ~ NA_character_,
    TRUE ~ as.character(gndr)
  ))
# Ensuring tables to not include NA variables
table(france_data$happy)
## 
##    0    1    2    3    4    5    6    7    8    9   10 
##   88   56  182  336  505 2286 1831 3943 5519 2345 1586
table(france_data$imprich)
## 
##     Important Not Important 
##          4940         13737
table(france_data$gndr)
## 
## Female   Male 
##  10018   8659
# Naming model as "france_model_1" with outcome variable "happy" and explanatory variable "imprich"
france_model_1 <- lm(happy ~ imprich, data = france_data)
# Extract coefficents and intercept 
coefficients <- coef(france_model_1)

print(coefficients)
##          (Intercept) imprichNot Important 
##           7.17368421           0.04361214
# Produce table output 
tidy(france_model_1)
## # A tibble: 2 × 5
##   term                 estimate std.error statistic p.value
##   <chr>                   <dbl>     <dbl>     <dbl>   <dbl>
## 1 (Intercept)            7.17      0.0255    281.     0    
## 2 imprichNot Important   0.0436    0.0298      1.46   0.143
# Improving table presentation
tidy(france_model_1) |>
knitr::kable(digits = 3)
term estimate std.error statistic p.value
(Intercept) 7.174 0.026 280.945 0.000
imprichNot Important 0.044 0.030 1.465 0.143
# Produce full summary output
summary(france_model_1)
## 
## Call:
## lm(formula = happy ~ imprich, data = france_data)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -7.2173 -1.2173  0.7827  0.8263  2.8263 
## 
## Coefficients:
##                      Estimate Std. Error t value Pr(>|t|)    
## (Intercept)           7.17368    0.02553 280.945   <2e-16 ***
## imprichNot Important  0.04361    0.02977   1.465    0.143    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 1.795 on 18675 degrees of freedom
## Multiple R-squared:  0.0001149,  Adjusted R-squared:  6.134e-05 
## F-statistic: 2.146 on 1 and 18675 DF,  p-value: 0.143
# Get equation output with equatiomatic
remotes::install_github("datalorax/equatiomatic")
## Skipping install of 'equatiomatic' from a github remote, the SHA1 (39e8c3ea) has not changed since last install.
##   Use `force = TRUE` to force installation
equatiomatic::extract_eq(france_model_1, use_coefs = TRUE)

\[ \operatorname{\widehat{happy}} = 7.17 + 0.04(\operatorname{imprich}_{\operatorname{Not\ Important}}) \]

# Produce a regression table of the outcome variable "happy" with the main explanatory variable "imprich"
modelsummary(
  list(france_model_1),
  fmt = 1,
  estimate = c("{estimate} ({std.error}){stars}"),
  statistic = NULL,
  title = "Table 2. Regression models predicting happiness (scale 0 to 10)")
Table 2. Regression models predicting happiness (scale 0 to 10)
 (1)
(Intercept) 7.2 (0.0)***
imprichNot Important 0.0 (0.0)
Num.Obs. 18677
R2 0.000
R2 Adj. 0.000
AIC 74852.5
BIC 74876.0
Log.Lik. −37423.244
RMSE 1.79
# Produce a multivariate regression table of the outcome variable "happy" with variables "imprich" and "gndr"
france_model_2 <- lm(happy ~ imprich + gndr, data = france_data)

modelsummary(
  list(france_model_1, france_model_2),
  fmt = 1,
  estimate = c("{estimate} ({std.error}){stars}"),
  statistic = NULL,
  title = "Table 2. Regression models predicting happiness (scale 0 to 10)")
Table 2. Regression models predicting happiness (scale 0 to 10)
 (1)   (2)
(Intercept) 7.2 (0.0)*** 7.2 (0.0)***
imprichNot Important 0.0 (0.0) 0.0 (0.0)
gndrMale 0.0 (0.0)
Num.Obs. 18677 18677
R2 0.000 0.000
R2 Adj. 0.000 0.000
AIC 74852.5 74854.4
BIC 74876.0 74885.8
Log.Lik. −37423.244 −37423.218
RMSE 1.79 1.79
# Produce a regression table of the outcome variable "happy", using the interaction variables "imprich" and "gndr"
france_model_3 <- lm(happy ~ imprich + gndr + imprich * gndr, data = france_data)

modelsummary(
  list(france_model_1, france_model_2, france_model_3),
  fmt = 1,
  estimate = c("{estimate} ({std.error}){stars}"),
  statistic = NULL,
  title = "Table 2. Regression models predicting happiness (scale 0 to 10)")
Table 2. Regression models predicting happiness (scale 0 to 10)
 (1)   (2)   (3)
(Intercept) 7.2 (0.0)*** 7.2 (0.0)*** 7.1 (0.0)***
imprichNot Important 0.0 (0.0) 0.0 (0.0) 0.1 (0.0)*
gndrMale 0.0 (0.0) 0.1 (0.1)+
imprichNot Important × gndrMale −0.1 (0.1)*
Num.Obs. 18677 18677 18677
R2 0.000 0.000 0.000
R2 Adj. 0.000 0.000 0.000
AIC 74852.5 74854.4 74852.4
BIC 74876.0 74885.8 74891.6
Log.Lik. −37423.244 −37423.218 −37421.225
RMSE 1.79 1.79 1.79
# Plot interaction effects for further visualization of data
france_model_4 <- lm(happy ~ imprich + gndr + imprich * gndr, data = france_data)

interaction_plot <- effect("imprich * gndr", france_model_4, na.rm=TRUE)

plot(interaction_plot,
     main = "Figure 2: Importance of wealth on happiness by gender",
     xlab = "Importance of wealth",
     ylab = "Happiness")