Mission 1

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" "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"
ess <- read_fst("All-ESS-Data.fst")

Mission 2

uk_data <- ess %>% 
  filter(cntry == "GB") 

write_fst(uk_data, "/Users/chenyiran/Desktop/SOC202/uk_data.fst")

Mission 3

Clean your environment and load in the filtered dataset.

 rm(list=ls()); gc()
##           used (Mb) gc trigger   (Mb) limit (Mb)   max used    (Mb)
## Ncells 1262865 67.5    2132658  113.9         NA    2132658   113.9
## Vcells 2152782 16.5 1257008054 9590.3      16384 1361161862 10384.9
df <- read_fst("/Users/chenyiran/Desktop/SOC202/uk_data.fst")

Mission 4

Produce and save a data summary output (using data summary skim) for potential outcomes of interest on a similar scale (e.g., 0-10, or 1 to 6, or binary). Add a title. You can do so while coding (explore package information for flextable and/or modelsummary) or add it directly in the word file. Title should be something like: Table 1: Descriptive Statistics for outcome variables. You can alter the title as you see fit.

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

uk_data <- df

uk_data_table_subset <- uk_data %>%
  mutate(
    pplhlp = ifelse(pplhlp %in% c(77, 88, 99), NA, pplhlp), 
    trstprl = ifelse(trstprl %in% c(77, 88, 99), NA, trstprl), 
    atcherp = ifelse(atcherp %in% c(77, 88, 99), NA, atcherp),
    brncntr = ifelse(brncntr == 2, 0, ifelse(brncntr %in% c(7,8,9), NA, brncntr))
  )
uk_data_v2 <- uk_data_table_subset %>%
  rename(
    `Most of the time people helpful or mostly looking out for themselves` = pplhlp,
    `Trust in the country's parliament` = trstprl,
    `How emotionally attached to Europe` = atcherp
  )

summary_table <- datasummary_skim(uk_data_v2 %>% select(`Most of the time people helpful or mostly looking out for themselves`, `Trust in the country's parliament`, `How emotionally attached to Europe`), output = "flextable")
## 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

Unique (#)

Missing (%)

Mean

SD

Min

Median

Max

Most of the time people helpful or mostly looking out for themselves

12

0

5.7

2.0

0.0

6.0

10.0

Trust in the country's parliament

12

2

4.3

2.4

0.0

4.0

10.0

How emotionally attached to Europe

12

75

4.6

2.7

0.0

5.0

10.0

flextable::save_as_docx(summary_table, path = "summary_table.docx", 
                       width = 7.0, height = 7.0) 

Mission 5

Produce and save a data summary output (using data summary skim) for socio-demographic variables. Add a title. You can do so while coding (explore package information for flextable and/or modelsummary) or add it directly in the word file. Title should be something like: Table 1: Descriptive Statistics for socio-demographic variables. You can alter the title as you see fit.

uk_data_sociodemographic <- uk_data %>%
  mutate(
    gndr = ifelse(gndr == 2, 0, ifelse(gndr %in% c(9), NA, gndr)), 
    rlgblg = ifelse(rlgblg == 2, 0, ifelse(rlgblg %in% c(7,8,9), NA, rlgblg)),
    brncntr = ifelse(brncntr == 2, 0, ifelse(brncntr %in% c(7,8,9), NA, brncntr)),
  )
uk_data_sociodemographic_2 <- uk_data_sociodemographic %>%
  rename(
    `Gender` = gndr,
    `Belonging to particular religion or denomination` = rlgblg,
    `Born in the country` = brncntr
  )

summary_table_sociodemographic <- datasummary_skim(uk_data_sociodemographic_2 %>% select(`Gender`,`Belonging to particular religion or denomination`,`Born in the country`), output = "flextable")
## 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_sociodemographic

Unique (#)

Missing (%)

Mean

SD

Min

Median

Max

Gender

3

0

0.4

0.5

0.0

0.0

1.0

Belonging to particular religion or denomination

3

0

0.5

0.5

0.0

0.0

1.0

Born in the country

3

0

0.9

0.3

0.0

1.0

1.0

flextable::save_as_docx(summary_table_sociodemographic, path = "summary_table_sociodemographic.docx", 
                       width = 7.0, height = 7.0) 

Mission 7

Produce a visualization between a categorical variable (e.g, one of the recoded socio-demographic variables – see below or last tutorial) and an outcome of interest. You can play around with geom(). Focus on computing as average using the aggregate function. Save the plot.

avg_atcherp_by_year <- aggregate(atcherp ~ year + brncntr, data=uk_data_table_subset, mean)

p1 <- ggplot(avg_atcherp_by_year, aes(x=year, y=atcherp, color=as.factor(brncntr))) + 
  geom_line(aes(group=brncntr)) +
  labs(title="Mean of Emotional Attachment to Europe by Survey Year", 
       subtitle = "for those that born in the UK vs. not in UK",
       x="Survey Year", 
       y="Average Emotional Attachment to Europe") +
  scale_color_discrete(name="Born In the Country", labels=c("No", "Yes")) +
  theme_minimal() 
p1

## Mission 8

Alter some of the criteria with your aggregate. For example, only looking at those with BA relative to a specified range of values of interest for your outcome or particular category. Then, visualize again. Save the plot.

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

avg_atcherp_by_yrbrn <- aggregate(atcherp ~ yrbrn, data=subset(uk_data_table_subset, brncntr == 1 & yrbrn >= 1960 & yrbrn <= 2000), FUN=mean)

p2 <- ggplot(avg_atcherp_by_yrbrn, aes(x=yrbrn, y=atcherp)) + 
  geom_point(aes(), size=3) +  
  geom_smooth(aes(), se=FALSE) +  
  labs(title="Mean of Emotional Attachment to Europe by Year of Birth",
       subtitle = "for those who born in UK",
       x="Birth Year", 
       y="Average",
       color="Legend") +
  theme_minimal()

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