# List of packages
packages <- c("tidyverse", "modelsummary", "forcats", "RColorBrewer", 
              "fst", "viridis", "knitr", "kableExtra", "rmarkdown", "ggridges", "viridis", "questionr","infer","dplyr")

# 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.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: 'kableExtra'
## 
## 
## The following object is masked from 'package:dplyr':
## 
##     group_rows
## [[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] "kableExtra"   "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] "rmarkdown"    "kableExtra"   "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"    "kableExtra"   "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"        
## 
## [[11]]
##  [1] "ggridges"     "rmarkdown"    "kableExtra"   "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] "questionr"    "ggridges"     "rmarkdown"    "kableExtra"   "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"        "questionr"    "ggridges"     "rmarkdown"    "kableExtra"  
##  [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] "infer"        "questionr"    "ggridges"     "rmarkdown"    "kableExtra"  
##  [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 Research project")
ess <- read_fst("All-ESS-Data.fst")
France_data <- ess %>%
  filter(cntry == "FR")
table(France_data$trstplt)
## 
##    0    1    2    3    4    5    6    7    8    9   10   77   88 
## 2642 1566 2738 2959 2580 3615 1460  850  362   71   49   20  126
table(France_data$tvtot)
## 
##    0    1    2    3    4    5    6    7   77   88 
##  605  703 1466 1788 1993 2044 1626 2752    1    3
France_data <- ess %>% 
  filter(cntry == "FR") %>% 
  mutate(
    tvtot = ifelse(tvtot %in% c(77, 88), NA, tvtot), 
    trstplt = ifelse(trstplt %in% c(77, 88), NA, trstplt), 
  )
table(France_data$tvtot)
## 
##    0    1    2    3    4    5    6    7 
##  605  703 1466 1788 1993 2044 1626 2752
datasummary_skim(France_data %>% select(tvtot, trstplt))
Unique (#) Missing (%) Mean SD Min Median Max
tvtot 9 32 4.3 2.1 0.0 4.0 7.0
trstplt 12 1 3.3 2.2 0.0 3.0 10.0
unique(France_data$tvtot)
## [1]  3  4  0  5  2  6  7  1 NA
unique(France_data$trstplt)
##  [1]  5  3  0  7  2  1  6  9  4  8 10 NA
France_data <- France_data %>% filter(!is.na(tvtot))
France_data <- France_data %>% filter(!is.na(trstplt))
unique(France_data$tvtot)
## [1] 3 4 0 5 2 6 7 1
unique(France_data$trstplt)
##  [1]  5  3  0  7  2  1  6  9  4  8 10
table(France_data$tvtot)
## 
##    0    1    2    3    4    5    6    7 
##  603  697 1458 1777 1988 2030 1620 2737
table(France_data$trstplt)
## 
##    0    1    2    3    4    5    6    7    8    9   10 
## 1809 1125 1911 2041 1774 2454  932  538  251   45   30
tab_dat <- France_data
mytab <- table(tab_dat$tvtot, tab_dat$trstplt)
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]        [,6]
## [1,] 0.006544906 0.004070215 0.006913939 0.007384274 0.006418277 0.008878496
## [2,] 0.007565173 0.004704710 0.007991733 0.008535389 0.007418804 0.010262540
## [3,] 0.015824996 0.009841415 0.016717284 0.017854514 0.015518819 0.021467407
## [4,] 0.019287392 0.011994647 0.020374907 0.021760955 0.018914225 0.026164323
## [5,] 0.021577566 0.013418885 0.022794212 0.024344839 0.021160090 0.029271060
## [6,] 0.022033431 0.013702382 0.023275780 0.024859166 0.021607134 0.029889463
## [7,] 0.017583329 0.010934906 0.018574760 0.019838349 0.017243132 0.023852675
## [8,] 0.029707143 0.018474591 0.031382172 0.033517014 0.029132377 0.040299241
##             [,7]        [,8]         [,9]        [,10]        [,11]
## [1,] 0.003371947 0.001946467 0.0009081102 0.0001628086 0.0001085391
## [2,] 0.003897590 0.002249897 0.0010496730 0.0001881884 0.0001254589
## [3,] 0.008153066 0.004706384 0.0021957291 0.0003936566 0.0002624377
## [4,] 0.009936899 0.005736107 0.0026761390 0.0004797859 0.0003198572
## [5,] 0.011116800 0.006417209 0.0029939023 0.0005367554 0.0003578369
## [6,] 0.011351662 0.006552784 0.0030571537 0.0005480953 0.0003653969
## [7,] 0.009058962 0.005229315 0.0024396990 0.0004373962 0.0002915975
## [8,] 0.015305172 0.008834960 0.0041218866 0.0007389836 0.0004926558
ftab <- N * ptab
cat("Table of Expected Frequencies:\n")
## Table of Expected Frequencies:
print(ftab)
##           [,1]      [,2]      [,3]      [,4]      [,5]     [,6]      [,7]
## [1,]  84.49473  52.54648  89.25895  95.33098  82.85995 114.6214  43.53184
## [2,]  97.66638  60.73780 103.17328 110.19187  95.77676 132.4894  50.31789
## [3,] 204.30070 127.05267 215.82014 230.50178 200.34795 277.1442 105.25608
## [4,] 249.00023 154.85089 263.04005 280.93393 244.18265 337.7814 128.28536
## [5,] 278.56638 173.23780 294.27328 314.29187 273.17676 377.8894 143.51789
## [6,] 284.45159 176.89775 300.49032 320.93184 278.94810 385.8730 146.54996
## [7,] 227.00077 141.16964 239.80015 256.11309 222.60883 307.9380 116.95120
## [8,] 383.51921 238.50697 405.14384 432.70465 376.09899 520.2632 197.58978
##           [,8]     [,9]    [,10]    [,11]
## [1,]  25.12889 11.72370 2.101859 1.401239
## [2,]  29.04617 13.55128 2.429512 1.619675
## [3,]  60.75941 28.34686 5.082107 3.388071
## [4,]  74.05314 34.54895 6.194036 4.129357
## [5,]  82.84617 38.65128 6.929512 4.619675
## [6,]  84.59644 39.46785 7.075910 4.717273
## [7,]  67.51046 31.49651 5.646785 3.764524
## [8,] 114.05933 53.21356 9.540279 6.360186
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: 156.7326
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 = 156.73, df = 70, p-value = 1.369e-08
h_test <- France_data %>%
  specify(explanatory = tvtot, 
          response = trstplt) %>% 
  hypothesize(null = "independence") %>%
  calculate(stat = "slope")
## Message: The independence null hypothesis does not inform calculation of the
## observed statistic (a slope) and will be ignored.
print(h_test$stat)
##       tvtot 
## -0.01146837
ht_test <- France_data %>%
  specify(tvtot ~ trstplt ) %>% 
  hypothesize(null = "independence") %>%
    generate(reps = 1000, type = "permute") %>% 
  calculate(stat = "slope") 
p_val <- ht_test %>% # 
  get_pvalue(obs_stat = test_stat, direction = "greater")
## 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
conf_int <- ht_test%>%
  get_confidence_interval(level = 0.95, type = "percentile")


ht_test %>%
  visualize(data, bins = 10, method = "simulation", dens_color = "black") +
  shade_p_value(obs_stat = test_stat, direction = "greater") +
  shade_confidence_interval(endpoints = conf_int)
## Warning in min(diff(unique_loc)): no non-missing arguments to min; returning
## Inf

test_stat <- 330.3334

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

ht_test %>%
  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(ht_test$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

France_data <- France_data %>%
  mutate(
    tvtime = case_when(
      tvtot %in% 0:0.5 ~ "1",                    
      tvtot %in% 0.5:1 ~ "2",                     
      tvtot %in% 1:2 ~ "3",
      tvtot %in% 2:3 ~ "4",
      tvtot %in% c(77, 88, 99) ~ NA_character_      
    ),
    tvtime = factor(tvtime, levels = c("1", "2", "3", "4"),
                 labels = c("less than 1 hr", "around 1 hrs", "around 2 hrs", "around 3 hrs")),
    
    age = 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)
    ),

    trust = case_when(
      trstplt %in% 0:3 ~ "1",                    
      trstplt %in% 3:4 ~ "2",                     
      trstplt %in% 4:5 ~ "3",
      trstplt %in% 5:6 ~ "4",
      trstplt %in% 6:7 ~ "5",                     
      trstplt %in% 7:8 ~ "6",
      trstplt %in% 8:9 ~ "7",
      trstplt %in% 9:10 ~ "8",
    ),
      
          edulvla = edulvla %>%
    na_if(55) %>%
    na_if(88),

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

   educ = case_when(
    essround < 5 & edulvla == 5 ~ 1,
    essround >= 5 & edulvlb > 600 ~ 1,
    TRUE ~ 0
    ),
    
    Party = case_when(
      lrscale %in% 0:3 ~ "Left",                    
      lrscale %in% 7:10 ~ "Right",                     
      lrscale %in% 4:6 ~ "Moderate",                  
      lrscale %in% c(77, 88, 99) ~ NA_character_      
  )
   )
model1 <- lm(trust ~ tvtime, data = France_data, weights = weight)
model2 <- lm(trust ~ tvtime + age, data = France_data, weights = weight)
model3 <- lm(trust ~ tvtime + age + educ*Party ,  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)
tvtimearound 2 hrs 0.1 (0.1) 0.1 (0.1) 0.0 (0.1)
tvtimearound 3 hrs 0.3 (0.1)+ 0.2 (0.1)+ 0.0 (0.1)
age1997 0.8 (0.3)* 1.0 (0.3)**
age1998 0.7 (0.4)+ 0.6 (0.4)
age1999 −0.4 (0.6) −0.3 (0.6)
age2 0.2 (0.2) 0.1 (0.2)
age2000 1.3 (1.5) 1.2 (1.4)
age3 0.1 (0.2) 0.0 (0.2)
age4 0.1 (0.2) −0.2 (0.2)
age7777 0.1 (1.9) 0.4 (1.8)
educ 0.8 (0.2)***
PartyModerate 0.2 (0.1)
PartyRight 0.1 (0.2)
educ × PartyModerate −0.6 (0.2)*
educ × PartyRight −0.5 (0.3)+
Num.Obs. 696 696 663
R2 0.005 0.021 0.063
R2 Adj. 0.002 0.007 0.041
AIC 2480.8 2485.6 2259.3
BIC 2499.0 2540.1 2335.8
Log.Lik. −1236.421 −1230.799 −1112.673
RMSE 1.26 1.26 1.26
table(ess$tvtot)
## 
##     0     1     2     3     4     5     6     7    77    88    99 
## 13055 18377 45705 46056 55550 43202 40829 73214    46   787   143
table(ess$trstplt)
## 
##     0     1     2     3     4     5     6     7     8     9    10    77    88 
## 79525 42046 56947 63008 55417 81569 45397 34012 15562  3918  3106   576  8690 
##    99 
##   782
France_data <- ess %>%
  filter(cntry == "FR") %>% 
  mutate(
    tvtot = ifelse(tvtot == 2, 0, ifelse(tvtot %in% c(7, 8, 9), NA, tvtot)), 
  
    trstplt = ifelse(trstplt %in% c(77, 88, 99), NA, trstplt), 

  )
trust_by_time <- France_data %>%
  group_by(trstplt) %>%
  summarize(mean_trust = mean(tvtot, na.rm = TRUE))
trust_by_time
## # A tibble: 12 × 2
##    trstplt mean_trust
##      <dbl>      <dbl>
##  1       0       3.33
##  2       1       3.24
##  3       2       3.46
##  4       3       3.39
##  5       4       3.26
##  6       5       3.47
##  7       6       3.38
##  8       7       3.19
##  9       8       2.98
## 10       9       3.51
## 11      10       2.88
## 12      NA       3.17
ggplot(France_data, aes(x = tvtot, y = trstplt)) +
  geom_point(color = "blue", size = 1) +  # Points to plot each observation
  labs(title = "TV Watching Time vs Trust in Politicians in France", 
       x = "TV Watching Time", 
       y = "Trust in Politicians") +
  theme_minimal()
## Warning: Removed 8861 rows containing missing values (`geom_point()`).

# 'trust_by_time' is your dataset, with 'mean_trust' representing the average TV watching time and 'trstplt' representing trust in politicians.

ggplot(trust_by_time, aes(x = trstplt, y = mean_trust)) +
  geom_line(color = "blue", size = 1) +  
  geom_point(color = "red", size = 3) +  # Points to highlight each value
  labs(title = "Trust in Politicians vs. Average Time Spent Watching TV", 
       x = "Trust in Politicians (0-10)", 
       y = "Average TV Watching Time") +
  ylim(0, 10) +  # Setting the y-axis limits from 0 to 10
  theme_minimal()
## Warning: Removed 1 row containing missing values (`geom_line()`).
## Warning: Removed 1 rows containing missing values (`geom_point()`).

```