# List of packages
packages <- c("tidyverse", "modelsummary", "forcats", "RColorBrewer", 
              "fst", "viridis", "knitr", "rmarkdown", "ggridges", "viridis", "questionr", "flextable", "infer", "broom") # add any you need here

# Install packages if they aren't installed already
new_packages <- packages[!(packages %in% installed.packages()[,"Package"])]
if(length(new_packages)) install.packages(new_packages)

# Load the 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.4     ✔ tibble    3.2.1
## ✔ lubridate 1.9.3     ✔ 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"        
## 
## [[14]]
##  [1] "broom"        "infer"        "flextable"    "questionr"    "ggridges"    
##  [6] "rmarkdown"    "knitr"        "viridis"      "viridisLite"  "fst"         
## [11] "RColorBrewer" "modelsummary" "lubridate"    "forcats"      "stringr"     
## [16] "dplyr"        "purrr"        "readr"        "tidyr"        "tibble"      
## [21] "ggplot2"      "tidyverse"    "stats"        "graphics"     "grDevices"   
## [26] "utils"        "datasets"     "methods"      "base"
ess <- read_fst("All-ESS-Data.fst")

Filtering to country, recoding and cleaning variables of interest

replacements <- c(2002, 2004, 2006, 2008, 2010, 2012, 2014, 2016, 2018, 2020)
for(i in 1:10){
  ess$year[ess$essround == i] <- replacements[i]
}

# Filter for France and remove rows with NAs in 'happy' and 'netustm'
france_data <- ess %>%
  filter(cntry == "FR") %>%
  mutate(
    happy = ifelse(happy %in% c(77, 88, 99), NA, happy), 
    netustm = ifelse(netustm %in% c(6666, 7777, 8888, 9999), NA, netustm),
    chldhhe = ifelse(chldhhe %in% c(6, 7, 8, 9), NA, chldhhe)
  ) 

Making sure there are no NAs before proceeding.

# Remove rows with NAs
france_data <- france_data %>%
  filter(!is.na(happy),
         !is.na(netustm))

# Double-checking unique values and quick distribution
unique(france_data$happy)
##  [1]  7  6  8  9 10  5  3  4  1  2  0
unique(france_data$netustm)
##  [1]  120  240   90  180  150   75   30   60   45  360  600  300  420   15  540
## [16]  330  480  210    1  270  390  900    0   20  570  660   10  720   50  780
## [31]  450  840  105    5  183  690  510  239   80   40    3 1020  230    2  960
## [46]  135   21   61   86  181  121  160 1380  100  310   31   14   25   27  147
## [61]   44   18  490  165  405  110   38   55  630  128   35  188  320   63  750
## [76]  488  170  308 1080
table(france_data$happy)
## 
##    0    1    2    3    4    5    6    7    8    9   10 
##   13    8   31   55  104  398  368  976 1457  673  392

Using the infer package

Step 1: Calculate the test statistic of your sample

Important Note: to assign the appropriate test statistic, please refer to the summary table presented during lecture (specifically, slide 24)

happy_stat <- france_data %>%
  specify(explanatory = netustm, 
          response = happy) %>% 
  calculate(stat = "slope")

print(happy_stat$stat)
##      netustm 
## 1.553155e-05

Interpretation: The result of the linear regression analysis for the relationship between ‘netustm’ and ‘happy’ indicates that, on average, a one-unit increase in the ‘netustm’ variable is associated with a very small change in the ‘happy’ variable. The estimated slope, approximately 1.553e-05, suggests a positive relationship, implying that as the time spent on the internet (‘netustm’) increases, the reported level of happiness (‘happy’) tends to increase slightly.

However, it’s crucial to note that the magnitude of this change is extremely small. The statistical significance of this relationship is not provided in the information you shared. The significance level, often represented by the p-value, would be essential to determine whether this observed relationship is likely to be a real effect or could have occurred by random chance.

Step 2: Simulate the null distribution

# Storing the null distribution
null_distribution <- france_data %>%
  specify(explanatory = netustm, response = happy) %>%
  hypothesize(null = "independence") %>%
  generate(reps = 1000, type = "permute") %>% 
  calculate(stat = "slope")

# Print the null distribution
print(null_distribution)
## Response: happy (numeric)
## Explanatory: netustm (numeric)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate       stat
##        <int>      <dbl>
##  1         1  0.0000468
##  2         2  0.0000722
##  3         3 -0.0000885
##  4         4 -0.0000713
##  5         5  0.000384 
##  6         6  0.000117 
##  7         7  0.000179 
##  8         8  0.000110 
##  9         9  0.000282 
## 10        10  0.0000441
## # ℹ 990 more rows

Step 3: Calculate the p-value of your sample

p_val <- null_distribution %>% 
  get_pvalue(obs_stat = happy_stat, direction = "two-sided")

p_val
## # A tibble: 1 × 1
##   p_value
##     <dbl>
## 1    0.96

A p-value of 0.89 is quite high, indicating that the observed slope (relationship between netustm and happy) is likely to occur frequently under the null hypothesis of no association (independence). In other words, it suggests that the observed relationship in your data could very well be due to random chance.

Interpretation: High p-value (e.g., > 0.05): Fail to reject the null hypothesis.

Step 4: Visualize

null_distribution %>%
  visualize() +
  shade_p_value(obs_stat = happy_stat, direction = "two-sided")

null_distribution
## Response: happy (numeric)
## Explanatory: netustm (numeric)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate       stat
##        <int>      <dbl>
##  1         1  0.0000468
##  2         2  0.0000722
##  3         3 -0.0000885
##  4         4 -0.0000713
##  5         5  0.000384 
##  6         6  0.000117 
##  7         7  0.000179 
##  8         8  0.000110 
##  9         9  0.000282 
## 10        10  0.0000441
## # ℹ 990 more rows

Visualizing the null distribution alongside the observed test statistic, we can observe that the red line falls well within the null distribution. This indicates that the observed statistic is not considered unusual or extreme when compared to what would be expected under the null hypothesis. If the observed statistic were to fall within the null distribution, we would expect shaded red regions in the null distribution that are as (or more) extreme than our observed statistic. However, in this case, the observed statistic does not appear to be in an extreme region of the null distribution.

conf_int <- null_distribution %>%
  get_confidence_interval(level = 0.95, type = "percentile")


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

null_distribution
## Response: happy (numeric)
## Explanatory: netustm (numeric)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate       stat
##        <int>      <dbl>
##  1         1  0.0000468
##  2         2  0.0000722
##  3         3 -0.0000885
##  4         4 -0.0000713
##  5         5  0.000384 
##  6         6  0.000117 
##  7         7  0.000179 
##  8         8  0.000110 
##  9         9  0.000282 
## 10        10  0.0000441
## # ℹ 990 more rows

It’s also worth mentioning that the confidence interval (assuming a 95% confidence level) is considered, and it encompasses a range of values that are consistent with the null hypothesis. This further supports the conclusion that, based on the given p-value, we do not have sufficient evidence to reject the null hypothesis.

# Fit three linear regression models
model1 <- lm(happy ~ netustm, data = france_data)
model2 <- lm(happy ~ netustm + chldhhe, data = france_data)
model3 <- lm(happy ~ netustm + chldhhe + netustm*chldhhe, data = france_data)

# Use modelsummary to summarize the models
modelsummary(list(model1, model2, model3))
 (1)   (2)   (3)
(Intercept) 7.442 7.177 7.252
(0.037) (0.101) (0.147)
netustm 0.000 0.000 −0.001
(0.000) (0.000) (0.001)
chldhhe 0.149 0.101
(0.068) (0.098)
netustm × chldhhe 0.000
(0.000)
Num.Obs. 4475 2767 2767
R2 0.000 0.002 0.002
R2 Adj. 0.000 0.001 0.001
AIC 17218.8 10722.5 10724.0
BIC 17238.0 10746.2 10753.6
Log.Lik. −8606.409 −5357.237 −5356.997
RMSE 1.66 1.68 1.68
library(broom)
library(knitr)

# Assuming model3 is your regression model
model3 <- lm(happy ~ netustm + chldhhe + netustm*chldhhe, data = france_data)

# Use broom to tidy up the model
tidy_model <- tidy(model3)

# Print the coefficients
print(tidy_model)
## # A tibble: 4 × 5
##   term             estimate std.error statistic p.value
##   <chr>               <dbl>     <dbl>     <dbl>   <dbl>
## 1 (Intercept)      7.25      0.147       49.2     0    
## 2 netustm         -0.000636  0.000743    -0.855   0.392
## 3 chldhhe          0.101     0.0977       1.03    0.303
## 4 netustm:chldhhe  0.000295  0.000426     0.693   0.488
# Alternatively, you can use knitr to nicely format the coefficients
kable(tidy_model, format = "html")
term estimate std.error statistic p.value
(Intercept) 7.2519698 0.1474079 49.1966170 0.0000000
netustm -0.0006359 0.0007433 -0.8554769 0.3923614
chldhhe 0.1005606 0.0976823 1.0294665 0.3033506
netustm:chldhhe 0.0002953 0.0004261 0.6929936 0.4883718