Mission 1

# List of packages
packages <- c("tidyverse", "modelsummary", "forcats", "RColorBrewer", 
              "fst", "viridis", "knitr", "rmarkdown", "ggridges", "viridis", "questionr", "flextable", "infer") # 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.2     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.0
## ✔ ggplot2   3.4.2     ✔ tibble    3.2.1
## ✔ lubridate 1.9.2     ✔ tidyr     1.3.0
## ✔ purrr     1.0.1     
## ── 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"

Mission 2

library(fst)
#ess <- read_fst("All-ESS-Data.fst")
library(tidyverse)
#denmark_data <- ess %>% filter(cntry== "DK")
#write_fst(denmark_data,"soc/denmark_data.fst")

Mission 3

#rm(list=ls()); gc()

Mission 4 and 5

df <- read_fst("denmark_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(
    clsprty = ifelse(clsprty == 2, 0, ifelse(clsprty %in% c(7, 8, 9), NA, clsprty)), 
    stfdem = ifelse(stfdem %in% c(77, 88, 99), NA, stfdem), 
    trstplt = ifelse(trstplt %in% c(77, 88, 99), NA, trstplt) 
  )
library(modelsummary)
summary_table <- datasummary_skim(france_data_table_subset %>% select(clsprty, stfdem, trstplt), output = "flextable",title="Table 1. summary table of data statistics")
## 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. summary table of data statistics

Unique (#)

Missing (%)

Mean

SD

Min

Median

Max

clsprty

3

2

0.7

0.5

0.0

1.0

1.0

stfdem

12

2

7.3

2.0

0.0

8.0

10.0

trstplt

12

1

5.3

2.0

0.0

5.0

10.0

france_data_v2 <- france_data_table_subset %>%
  rename(
    `Feeling Close to a Party` = clsprty,
    `Satisfaction with Democracy` = stfdem,
    `Trust in Politicians` = trstplt
  )
summary_table_v2 <- datasummary_skim(france_data_v2 %>% select(`Feeling Close to a Party`,`Satisfaction with Democracy`, `Trust in Politicians`), output = "flextable",title="Table 2. summary table of data statistics of new name")
## 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
Table 2. summary table of data statistics of new name

Unique (#)

Missing (%)

Mean

SD

Min

Median

Max

Feeling Close to a Party

3

2

0.7

0.5

0.0

1.0

1.0

Satisfaction with Democracy

12

2

7.3

2.0

0.0

8.0

10.0

Trust in Politicians

12

1

5.3

2.0

0.0

5.0

10.0

Mission 6

# Calculate the mean of trstprl by year and clsprty
avg_trstprl_by_year <- aggregate(trstplt ~ year + clsprty, data=france_data_table_subset, mean)

# Storing plot as p1
p1 <- ggplot(avg_trstprl_by_year, aes(x=year, y=trstplt, color=as.factor(clsprty))) + 
  geom_line(aes(group=clsprty)) +
  labs(title="Mean of Trust in Politicians by Survey Year", 
       subtitle = "for those that feel close to a party vs. not in Denmark",
       x="Survey Year", 
       y="Average Trust in Politicians") +
  scale_color_discrete(name="Feel Close to a Party", labels=c("No", "Yes")) +
  theme_minimal()

p1

Mission 8

# Making sure it's clean
france_data_table_subset$yrbrn[france_data_table_subset$yrbrn %in% c(7777, 8888)] <- NA

avg_stfdem_by_yrbrn <- aggregate(stfdem ~ yrbrn, data=subset(france_data_table_subset, clsprty == 0 & yrbrn >= 1980 & yrbrn <= 2000), FUN=mean)

# Plot using ggplot
p2 <- ggplot(avg_stfdem_by_yrbrn, aes(x=yrbrn, y=stfdem)) + 
  geom_point(aes(), size=3) +   # Adds individual points
  geom_smooth(aes(), se=FALSE) +  # Adds smoothed line
  labs(title="Mean of Satisfaction of Democracy by Year of Birth",
       subtitle = "for those who do not feel close to any party in Denmark",
       x="Birth Year", 
       y="Average",
       color="Legend") +
  theme_minimal()

p2
## `geom_smooth()` using method = 'loess' and formula = 'y ~ x'

Mission 9

millennials_data <- df %>%filter( yrbrn > 1980 & yrbrn < 1997) 

boomers_data <- df %>% filter(yrbrn > 1945 & yrbrn < 1965)

# Clean the variables
millennials_data_cleaned <- millennials_data %>%
  mutate(
    ipeqopt = ifelse(ipeqopt %in% c(7, 8, 9), NA, ipeqopt),
    imprich = ifelse(imprich %in% c(7, 8, 9), NA, imprich),
    impfree = ifelse(impfree %in% c(7, 8, 9), NA, impfree)
  ) %>%
  group_by(yrbrn) %>%
  summarise(
    avg_imprich = mean(imprich, na.rm = TRUE),
    avg_ipeqopt = mean(ipeqopt, na.rm = TRUE),
    avg_impfree = mean(impfree, na.rm = TRUE)
  )

boomers_data_cleaned <- boomers_data %>%
  mutate(
    ipeqopt = ifelse(ipeqopt %in% c(7, 8, 9), NA, ipeqopt),
    imprich = ifelse(imprich %in% c(7, 8, 9), NA, imprich),
    impfree = ifelse(impfree %in% c(7, 8, 9), NA, impfree)
  ) %>%
  group_by(yrbrn) %>%
  summarise(
    avg_imprich = mean(imprich, na.rm = TRUE),
    avg_ipeqopt = mean(ipeqopt, na.rm = TRUE),
    avg_impfree = mean(impfree, na.rm = TRUE)
  )

# Create scatterplots with trend lines for average scores
ggplot() +
  geom_point(data = millennials_data_cleaned, aes(x = yrbrn, y = avg_imprich), color = "black", alpha = 0.6) +
  geom_point(data = boomers_data_cleaned, aes(x = yrbrn, y = avg_imprich), color = "black", alpha = 0.6) +
  geom_smooth(data = millennials_data_cleaned, aes(x = yrbrn, y = avg_imprich), method = "lm", formula = y ~ poly(x, 1), color = "black") +
  geom_smooth(data = boomers_data_cleaned, aes(x = yrbrn, y = avg_imprich), method = "lm", formula = y ~ poly(x, 1), color = "black") +
  labs(
    title = "Average imprich Score by Birth Year (Millennials vs. Boomers) in Denmark",
    x = "Year of Birth",
    y = "Average imprich"
  ) +
  scale_color_manual(values = c("black", "black")) +
  theme_bw()

# Mission 10

france_data <- france_data %>%
  mutate(
    # Set 'other' to NA for rounds 1-4
    edulvla = case_when(
      essround < 5 & edulvla == 55 ~ NA_real_,
      TRUE ~ edulvla
    ),
    # Set 'other' to NA for rounds 5 and later
    edulvlb = case_when(
      essround >= 5 & edulvlb == 5555 ~ NA_real_,
      TRUE ~ edulvlb
    ),
    # Create educ_level column
    educ_level = case_when(
      essround < 5 & edulvla == 5 ~ "BA",
      essround >= 5 & edulvlb > 600 ~ "BA",
      TRUE ~ "No BA"
    )
  )

# View the table of educ_level
table(france_data$educ_level)
## 
##    BA No BA 
##  4359  8049
# double check clean
france_data <- france_data %>%filter(!is.na(educ_level) & !is.na(clsprty))

# visualize
table(france_data$clsprty, france_data$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="Feeling close to a particular party in Denmark",
       x = "Feeling close (Y/N)",
      fill = "At least BA vs. Not")

Mission 14

# Calculate standard deviation for clsprty
sd_clsprty <- sd(france_data_table_subset$clsprty, na.rm = TRUE)

# Calculate sample size
n_clsprty <- sum(!is.na(france_data_table_subset$clsprty))

# Calculate standard error
se_clsprty <- sd_clsprty / sqrt(n_clsprty)

se_clsprty
## [1] 0.004114344

Reflection:

  1. issue you were able to resolve while working on missions (could potentially help others).

When I work the mission 2, since the dataset is large enough, so I need to setwd to read in data. This is what I learn from the tutorial. Otherwise, I will have the limitation issue.

When I do graph, I need to do some varibles recoding before or the R will tell me that the variable can not be found.

  1. issue you are currently dealing with with some detail; (c) what’s the emerging story, as of now, for your country/outcome of interest (i.e., even before modelling, what are you observing, noting, seeing that you wish to explore further). If you would like, add a ”hunch” about what might explain what you noted.

The country I am interested in Denmark. The outcome variable I am interested in is imprich.I use plot to see the average imprich by birth year. And I divide year mainly into two parts: Millennial and boomers. I will build a model further between average imprich and birth year. I would like to see whether they have a negative assoication between them.

The interesting story before modelling is that imprich decreases very much when years pass by. Also I would like to explore clsprty for this country as well.