Mission 1

library(fst)
setwd("~/SOC202/R Scripts (hw + tutorial)")
ess <- read_fst("All-ESS-Data.fst")

packages <- c("tidyverse", "modelsummary", "forcats", "RColorBrewer", 
              "fst", "viridis", "knitr", "rmarkdown", "ggridges", "viridis", "questionr", "flextable", "infer")

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: 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" "fstcore"   "fst"      
## [13] "stats"     "graphics"  "grDevices" "utils"     "datasets"  "methods"  
## [19] "base"     
## 
## [[2]]
##  [1] "modelsummary" "lubridate"    "forcats"      "stringr"      "dplyr"       
##  [6] "purrr"        "readr"        "tidyr"        "tibble"       "ggplot2"     
## [11] "tidyverse"    "fstcore"      "fst"          "stats"        "graphics"    
## [16] "grDevices"    "utils"        "datasets"     "methods"      "base"        
## 
## [[3]]
##  [1] "modelsummary" "lubridate"    "forcats"      "stringr"      "dplyr"       
##  [6] "purrr"        "readr"        "tidyr"        "tibble"       "ggplot2"     
## [11] "tidyverse"    "fstcore"      "fst"          "stats"        "graphics"    
## [16] "grDevices"    "utils"        "datasets"     "methods"      "base"        
## 
## [[4]]
##  [1] "RColorBrewer" "modelsummary" "lubridate"    "forcats"      "stringr"     
##  [6] "dplyr"        "purrr"        "readr"        "tidyr"        "tibble"      
## [11] "ggplot2"      "tidyverse"    "fstcore"      "fst"          "stats"       
## [16] "graphics"     "grDevices"    "utils"        "datasets"     "methods"     
## [21] "base"        
## 
## [[5]]
##  [1] "RColorBrewer" "modelsummary" "lubridate"    "forcats"      "stringr"     
##  [6] "dplyr"        "purrr"        "readr"        "tidyr"        "tibble"      
## [11] "ggplot2"      "tidyverse"    "fstcore"      "fst"          "stats"       
## [16] "graphics"     "grDevices"    "utils"        "datasets"     "methods"     
## [21] "base"        
## 
## [[6]]
##  [1] "viridis"      "viridisLite"  "RColorBrewer" "modelsummary" "lubridate"   
##  [6] "forcats"      "stringr"      "dplyr"        "purrr"        "readr"       
## [11] "tidyr"        "tibble"       "ggplot2"      "tidyverse"    "fstcore"     
## [16] "fst"          "stats"        "graphics"     "grDevices"    "utils"       
## [21] "datasets"     "methods"      "base"        
## 
## [[7]]
##  [1] "knitr"        "viridis"      "viridisLite"  "RColorBrewer" "modelsummary"
##  [6] "lubridate"    "forcats"      "stringr"      "dplyr"        "purrr"       
## [11] "readr"        "tidyr"        "tibble"       "ggplot2"      "tidyverse"   
## [16] "fstcore"      "fst"          "stats"        "graphics"     "grDevices"   
## [21] "utils"        "datasets"     "methods"      "base"        
## 
## [[8]]
##  [1] "rmarkdown"    "knitr"        "viridis"      "viridisLite"  "RColorBrewer"
##  [6] "modelsummary" "lubridate"    "forcats"      "stringr"      "dplyr"       
## [11] "purrr"        "readr"        "tidyr"        "tibble"       "ggplot2"     
## [16] "tidyverse"    "fstcore"      "fst"          "stats"        "graphics"    
## [21] "grDevices"    "utils"        "datasets"     "methods"      "base"        
## 
## [[9]]
##  [1] "ggridges"     "rmarkdown"    "knitr"        "viridis"      "viridisLite" 
##  [6] "RColorBrewer" "modelsummary" "lubridate"    "forcats"      "stringr"     
## [11] "dplyr"        "purrr"        "readr"        "tidyr"        "tibble"      
## [16] "ggplot2"      "tidyverse"    "fstcore"      "fst"          "stats"       
## [21] "graphics"     "grDevices"    "utils"        "datasets"     "methods"     
## [26] "base"        
## 
## [[10]]
##  [1] "ggridges"     "rmarkdown"    "knitr"        "viridis"      "viridisLite" 
##  [6] "RColorBrewer" "modelsummary" "lubridate"    "forcats"      "stringr"     
## [11] "dplyr"        "purrr"        "readr"        "tidyr"        "tibble"      
## [16] "ggplot2"      "tidyverse"    "fstcore"      "fst"          "stats"       
## [21] "graphics"     "grDevices"    "utils"        "datasets"     "methods"     
## [26] "base"        
## 
## [[11]]
##  [1] "questionr"    "ggridges"     "rmarkdown"    "knitr"        "viridis"     
##  [6] "viridisLite"  "RColorBrewer" "modelsummary" "lubridate"    "forcats"     
## [11] "stringr"      "dplyr"        "purrr"        "readr"        "tidyr"       
## [16] "tibble"       "ggplot2"      "tidyverse"    "fstcore"      "fst"         
## [21] "stats"        "graphics"     "grDevices"    "utils"        "datasets"    
## [26] "methods"      "base"        
## 
## [[12]]
##  [1] "flextable"    "questionr"    "ggridges"     "rmarkdown"    "knitr"       
##  [6] "viridis"      "viridisLite"  "RColorBrewer" "modelsummary" "lubridate"   
## [11] "forcats"      "stringr"      "dplyr"        "purrr"        "readr"       
## [16] "tidyr"        "tibble"       "ggplot2"      "tidyverse"    "fstcore"     
## [21] "fst"          "stats"        "graphics"     "grDevices"    "utils"       
## [26] "datasets"     "methods"      "base"        
## 
## [[13]]
##  [1] "infer"        "flextable"    "questionr"    "ggridges"     "rmarkdown"   
##  [6] "knitr"        "viridis"      "viridisLite"  "RColorBrewer" "modelsummary"
## [11] "lubridate"    "forcats"      "stringr"      "dplyr"        "purrr"       
## [16] "readr"        "tidyr"        "tibble"       "ggplot2"      "tidyverse"   
## [21] "fstcore"      "fst"          "stats"        "graphics"     "grDevices"   
## [26] "utils"        "datasets"     "methods"      "base"

Mission 2

sweden_data <- ess %>% 
  filter(cntry == "SE") 

write_fst(sweden_data, "~/SOC202/R Scripts (hw + tutorial)/Maa_Cassiopeia_Project_202/sweden_data.fst")

Mission 3

rm(list=ls()); gc()
##           used (Mb) gc trigger    (Mb)   max used    (Mb)
## Ncells 1259136 67.3    2271145   121.3    1828174    97.7
## Vcells 2128073 16.3 1504471041 11478.3 1354705062 10335.6
df <- read_fst("~/SOC202/R Scripts (hw + tutorial)/Maa_Cassiopeia_Project_202/sweden_data.fst")

Mission 4

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]
}

sweden_data <- df

sweden_data_table_subset <- sweden_data %>%
  mutate(
    wrclmch = ifelse(wrclmch %in% c(7, 8, 9), NA, wrclmch),
    netusoft = ifelse(netusoft %in% c(7, 8, 9), NA, netusoft),
    impenv = ifelse(impenv %in% c(7, 8, 9), NA, impenv),
    trstun = ifelse(trstun %in% c(77, 88, 99), NA, trstun))

sweden_data_table_subset <- sweden_data_table_subset %>%
  rename(
    `How worried about climate change` = wrclmch,
    `Internet use, how often` = netusoft,
    `Important to care for nature and environment` = impenv,  
    `Trust in the United Nations` = trstun,
  )

summary_table_v1 <- datasummary_skim(sweden_data_table_subset %>% select(`How worried about climate change`,`Internet use, how often`,`Important to care for nature and environment`,`Trust in the United Nations`), output = "flextable",
  title ="Table 1: Descriptive Statistics for outcome 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_v1
Table 1: Descriptive Statistics for outcome variables

Unique (#)

Missing (%)

Mean

SD

Min

Median

Max

How worried about climate change

7

79

3.0

0.9

1.0

3.0

6.0

Internet use, how often

6

71

4.6

1.1

1.0

5.0

5.0

Important to care for nature and environment

7

20

2.3

1.1

1.0

2.0

6.0

Trust in the United Nations

12

5

6.2

2.1

0.0

7.0

10.0

Mission 5

sweden_data_table_subset <- sweden_data_table_subset %>%
  mutate(
    gndr = ifelse(gndr %in% c(9), NA, gndr),
    edulvlb = ifelse(edulvlb %in% c(5555, 7777, 8888, 9999), NA, edulvlb),
    lrscale = ifelse(lrscale %in% c(77, 88, 99), NA, lrscale),
    tporgwk = ifelse(tporgwk %in% c(66, 77, 88, 99), NA, tporgwk),
    domicil = ifelse(domicil %in% c(7, 8, 9), NA, domicil))

sweden_data_table_subset <- sweden_data_table_subset %>%
  rename(
    `Gender` = gndr,
    `Highest level of education` = edulvlb,
    `Placement on left-right scale` = lrscale,
    `What type of organisation work/worked for` = tporgwk,
    `Area Living in` = domicil
  )

summary_table_v2 <- datasummary_skim(sweden_data_table_subset %>% select(`Gender`,`Highest level of education`,`Placement on left-right scale`,`What type of organisation work/worked for`,`Area Living in`), output = "flextable",
  title ="Table 2: Descriptive Statistics for socio-demographic 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_v2
Table 2: Descriptive Statistics for socio-demographic variables

Unique (#)

Missing (%)

Mean

SD

Min

Median

Max

Gender

3

0

1.5

0.5

1.0

2.0

2.0

Highest level of education

15

43

411.4

191.4

0.0

323.0

800.0

Placement on left-right scale

12

4

5.2

2.3

0.0

5.0

10.0

What type of organisation work/worked for

7

35

3.1

1.4

1.0

4.0

6.0

Area Living in

6

0

2.9

1.2

1.0

3.0

5.0

Mission 6

trust_by_year <- sweden_data_table_subset %>%
  group_by(year) %>%
  summarize(mean_trstun = mean(`Trust in the United Nations`, na.rm = TRUE))
trust_by_year
## # A tibble: 10 × 2
##     year mean_trstun
##    <dbl>       <dbl>
##  1  2002        6.58
##  2  2004        6.32
##  3  2006        6.41
##  4  2008        6.42
##  5  2010        6.34
##  6  2012        6.27
##  7  2014        6.39
##  8  2016        6.16
##  9  2018        6.32
## 10  2020        5.48
task6plot <- ggplot(trust_by_year, aes(x = year, y = mean_trstun)) +
  geom_line(color = "blue", size = 1) +
  geom_point(color = "red", size = 3) +
  labs(title = "Trust in the United Nations in Sweden (2002-2020)", 
       x = "Survey Year", 
       y = "Trust scale (0-10)") +
  ylim(0, 10) +
  theme_minimal()
## 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.
task6plot

ggsave(filename = "task6plot.pdf", plot = task6plot, device = "pdf", width = 6, height = 4)

Mission 7

sweden_data_table_subset <- sweden_data_table_subset %>%
  mutate(
    `Placement on left-right scale` = case_when(
      `Placement on left-right scale` %in% c(0:5) ~ "Left",
      `Placement on left-right scale` %in% c(6:10) ~ "Right",
      `Placement on left-right scale` %in% c(77, 88, 99) ~ NA_character_,
      TRUE ~ as.character(`Placement on left-right scale`)
    )
  )
table(sweden_data_table_subset$`Placement on left-right scale`)
## 
##  Left Right 
## 10068  7406
avg_trstun_by_year <- aggregate(`Trust in the United Nations` ~ year + `Placement on left-right scale`, data=sweden_data_table_subset, mean)

task7plot <- ggplot(avg_trstun_by_year, aes(x=year, y=`Trust in the United Nations`, color=as.factor(`Placement on left-right scale`))) + 
  geom_line(aes(group=`Placement on left-right scale`)) +
  labs(title="Mean of Trust in the United Nations by Survey Year", 
       subtitle = "For Placement on left-right scale in Sweden",
       x="Survey Year", 
       y="Average Trust in the United Nations") +
  scale_color_discrete(name="Placement on left-right scale", labels=c("Left", "Right")) +
  theme_minimal()
task7plot

ggsave(filename = "task7plot.pdf", plot = task7plot, device = "pdf", width = 6, height = 4)

Mission 8

sweden_data_table_subset$yrbrn[sweden_data_table_subset$yrbrn %in% c(7777, 8888, 9999)] <- NA

avg_trstun_by_yrbrn <- aggregate(`Trust in the United Nations` ~ yrbrn, data=subset(sweden_data_table_subset, `Placement on left-right scale` == "Right" & yrbrn >= 1980 & yrbrn <= 2000), FUN=mean)

task8plot <- ggplot(avg_trstun_by_yrbrn, aes(x=yrbrn, y=`Trust in the United Nations`)) + 
  geom_point(aes(), size=3) +
  geom_smooth(aes(), se=FALSE) +
  labs(title="Mean of Trust in the United Nations by Year of Birth",
       subtitle = "for those who places themselves on the right on the left-right scale in Sweden",
       x="Birth Year", 
       y="Average",
       color="Legend") +
  theme_minimal()
task8plot
## `geom_smooth()` using method = 'loess' and formula = 'y ~ x'

ggsave(filename = "task8plot.pdf", plot = task8plot, device = "pdf", width = 6, height = 4)
## `geom_smooth()` using method = 'loess' and formula = 'y ~ x'

Mission 9

library(fst)
setwd("~/SOC202/R Scripts (hw + tutorial)")
ess <- read_fst("All-ESS-Data.fst")

millennials_data <- ess %>%
  filter(cntry == "SE", yrbrn > 1980 & yrbrn < 1997) 

boomers_data <- ess %>%
  filter(cntry == "SE", yrbrn > 1945 & yrbrn < 1965)

millennials_data_cleaned <- millennials_data %>%
  mutate(
    wrclmch = ifelse(wrclmch %in% c(7, 8, 9), NA, wrclmch),
    netusoft = ifelse(netusoft %in% c(7, 8, 9), NA, netusoft),
    impenv = ifelse(impenv %in% c(7, 8, 9), NA, impenv),
    trstun = ifelse(trstun %in% c(77, 88, 99), NA, trstun)
  ) %>%
  group_by(yrbrn) %>%
  summarise(
    avg_wrclmch = mean(wrclmch, na.rm = TRUE),
    avg_netusoft = mean(netusoft, na.rm = TRUE),
    avg_impenv = mean(impenv, na.rm = TRUE),
    avg_trstun = mean(trstun, na.rm = TRUE)
  )

boomers_data_cleaned <- boomers_data %>%
  mutate(
    wrclmch = ifelse(wrclmch %in% c(7, 8, 9), NA, wrclmch),
    netusoft = ifelse(netusoft %in% c(7, 8, 9), NA, netusoft),
    impenv = ifelse(impenv %in% c(7, 8, 9), NA, impenv),
    trstun = ifelse(trstun %in% c(77, 88, 99), NA, trstun)
  ) %>%
  group_by(yrbrn) %>%
  summarise(
    avg_wrclmch = mean(wrclmch, na.rm = TRUE),
    avg_netusoft = mean(netusoft, na.rm = TRUE),
    avg_impenv = mean(impenv, na.rm = TRUE),
    avg_trstun = mean(trstun, na.rm = TRUE)
  )

ggplot() +
  geom_point(data = millennials_data_cleaned, aes(x = yrbrn, y = avg_trstun), color = "black", alpha = 0.6) +
  geom_point(data = boomers_data_cleaned, aes(x = yrbrn, y = avg_trstun), color = "black", alpha = 0.6) +
  geom_smooth(data = millennials_data_cleaned, aes(x = yrbrn, y = avg_trstun), method = "lm", formula = y ~ poly(x, 1), color = "black") +
  geom_smooth(data = boomers_data_cleaned, aes(x = yrbrn, y = avg_trstun), method = "lm", formula = y ~ poly(x, 1), color = "black") +
  labs(
    title = "Average trstun Score by Birth Year (Millennials vs. Boomers)",
    x = "Year of Birth",
    y = "Average trstun"
  ) +
  scale_color_manual(values = c("black", "black")) +
  theme_bw()

Mission 10

sweden_data_table_subset_clean <- sweden_data_table_subset %>%
  filter(!is.na(`Placement on left-right scale`) & !is.na(`Trust in the United Nations`))

sweden_probs <- sweden_data_table_subset_clean %>%
  count(`Trust in the United Nations`, `Placement on left-right scale`) %>%
  group_by(`Placement on left-right scale`) %>%
  mutate(prob = n / sum(n))

ggplot(sweden_probs, aes(x = as.factor(`Trust in the United Nations`), y = prob, color = `Placement on left-right scale`)) +
  geom_point() +
  geom_line(aes(group = `Placement on left-right scale`)) +
  labs(title = "Conditional Probabilities of Trust in United Nations",
       subtitle = "by Placement on left-right scale",
       x = "Trust Scale", 
       y = "Probability") +
  theme_minimal()