#Getting set up

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

# 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"

now we have to load the data in

library(fst)

ess <- read_fst("All-ESS-Data.fst")

Now into the homework

#Task 1

Choose the desired variables. The variables i chose are Physact (physical activity during the week), tvtot (Tv watching habits throughout the week), and Happy (how happy people are). I also chose to focus on Germany because i wanted to see what the central European countries were like on the physical and mental health scale.

Physact: https://ess-search.nsd.no/en/variable/73b3fce3-a47a-4b26-9a9a-264768522a58 Tvtot: https://ess-search.nsd.no/en/variable/query/tvtot/1 Happy: https://ess-search.nsd.no/en/variable/query/happy/1

table(ess$physact)
## 
##     0     1     2     3     4     5     6     7    77    88    99 
##  5231  2485  4089  5165  4222  5783  4089 22806    22   723    58
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$happy)
## 
##      0      1      2      3      4      5      6      7      8      9     10 
##   3933   3540   7343  13759  17016  52117  43707  87869 130802  76229  51006 
##     77     88     99 
##    330   2163    741

Next, filter for the years

table(ess$essround)
## 
##     1     2     3     4     5     6     7     8     9    10 
## 42359 47537 43000 56752 52458 54673 40185 44387 49519 59685
ess$year <- NA
replacements <- c(2002, 2004, 2006, 2008, 2010, 2012, 2014, 2016, 2018, 2020)
for(i in 1:10){
  ess$year[ess$essround == i] <- replacements[i]
}

Cleaning your data…

germany_data <- ess %>% # Start with the original 'ess' dataset
  filter(cntry == "DE") %>% # Filter the data to only include rows where country (cntry) is Germany, in this example ("GR")

mutate(
    physact = ifelse(physact == 2, 0, ifelse(physact %in% c(7, 8, 9), NA, physact)), 
    tvtot = ifelse(tvtot %in% c(77, 88, 99), NA, tvtot), 
    happy = ifelse(happy %in% c(77, 88, 99), NA, happy), 
  )

Let’s check to make sure we did it correctly

table(germany_data$physact)
## 
##   0   1   3   4   5   6  77  88 
## 390 131 286 260 400 246   1   5

#Make a data summary table

datasummary_skim(germany_data %>% select(physact, tvtot, happy))
Unique (#) Missing (%) Mean SD Min Median Max
physact 9 95 3.5 5.4 0.0 4.0 88.0
tvtot 9 41 4.2 2.0 0.0 4.0 7.0
happy 12 1 7.3 1.9 0.0 8.0 10.0

Looking at the data summary we can see that the mean for physact is lower than tvtot and happy. tvtot is not too much bigger compared to happy. We could infer here by looking at the high happiness median, and the higher tvot median (compared to physact) that people that watch more tv than exercising are happier during the week. These people’s happiness is influenced by the amount that they watch TV in a week.

#Task 2

WatchTv_by_year <- germany_data %>%
  group_by(year) %>%
  summarize(mean_tvtot = mean(tvtot, na.rm = TRUE))
WatchTv_by_year
## # A tibble: 10 × 2
##     year mean_tvtot
##    <dbl>      <dbl>
##  1  2002       4.37
##  2  2004       4.34
##  3  2006       4.25
##  4  2008       4.22
##  5  2010       4.19
##  6  2012       3.99
##  7  2014       3.90
##  8  2016     NaN   
##  9  2018     NaN   
## 10  2020     NaN

#Visualizing the mean graph

ggplot(WatchTv_by_year, aes(x = year, y = mean_tvtot)) +
  geom_line(color = "blue", size = 1) +  # Line to show the trend
  geom_point(color = "red", size = 3) +  # Points to highlight each year's value

labs(title = "Tv watching habits in germany (2002-2022)", 
       x = "Survey Year", 
       y = "Watch (0-10)") +
  ylim(0, 10) +  # Setting the y-axis limits from 0 to 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.
## Warning: Removed 3 rows containing missing values (`geom_line()`).
## Warning: Removed 3 rows containing missing values (`geom_point()`).

The habits of daily Tv watching did not vary much. The graph sits on a small constant decline. This demonstrates how between 2002 and 2014 the inclination to watch tv across Germany decreased. The data here however stops recording at 2014. THis could be a problem with the variable and in these caes it may be best to explore other variable options. Or there was a nation wide strike on television in Germany ;P

#Task 3

comparing our variable with 2 other countries. I am going to use France and Ireland.

ess_selected <- ess %>%
  filter(cntry %in% c("DE", "FR", "ES")) %>%
  mutate(tvtot = ifelse(tvtot %in% c(77, 88, 99), NA, tvtot))


task3plot <- ggplot(ess_selected, aes(x = reorder(cntry, -tvtot, FUN=median), y = tvtot, fill = cntry)) +
  geom_boxplot() +
  theme_minimal() + 
  theme(legend.position = "none") + 
  labs(title = "Boxplot comparison TV watching (Germany, France, Spain)", 
       x = "Country", 
       y = "Scale (0-10)")

task3plot
## Warning: Removed 25928 rows containing non-finite values (`stat_boxplot()`).

We can see from the graph that all the means of TV watching habits is the same for the 3 countries. Germany’s mean, though, is in the bottom quartile, like france. Spain’s mean is in the middle quartile range. Spain’s boxplot is longer, meaning it’s interquartile range is larger. and could have more outliers, causing the box plot to extend longer than the others. France and Germany do not have many outliers, though all the whiskers are the same length. Perhaps by extending the Y axis we could zoom out on the data and see a clearer picture of the outlying data.

#Task 4

germany_data <- germany_data %>%
  mutate(pdwrk_recode = case_when(
    pdwrk == 1 ~ 'yes',
    pdwrk == 0 ~ 'no', 
  ))

# check the recoded variable
table(germany_data$pdwrk_recode)
## 
##    no   yes 
## 15799 18626

This variable looks at the people in Germany have paid work status.

# compare with the original variable 
table(germany_data$pdwrk)
## 
##     0     1 
## 15799 18626

#Using crosstabs

tvtotpdwrk <- datasummary_crosstab(tvtot ~ pdwrk_recode, data = germany_data)
tvtotpdwrk
tvtot no yes All
0 N 313 455 768
% row 40.8 59.2 100.0
1 N 347 815 1162
% row 29.9 70.1 100.0
2 N 893 1955 2848
% row 31.4 68.6 100.0
3 N 991 1906 2897
% row 34.2 65.8 100.0
4 N 1448 2134 3582
% row 40.4 59.6 100.0
5 N 1467 1555 3022
% row 48.5 51.5 100.0
6 N 1734 1109 2843
% row 61.0 39.0 100.0
7 N 2529 826 3355
% row 75.4 24.6 100.0
All N 15799 18626 34425
% row 45.9 54.1 100.0

Here I used a second sociodemographic variable and made a second cross tab using education to be able to compare the data

germany_data <- germany_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(germany_data$educ_level)
## 
##    BA No BA 
##  8783 25642

This variable sees how many people in Germany have completed at least a bachelors degree.

tvtotedu <- datasummary_crosstab(tvtot ~ educ_level, data = germany_data)
tvtotedu
tvtot BA No BA All
0 N 290 478 768
% row 37.8 62.2 100.0
1 N 446 716 1162
% row 38.4 61.6 100.0
2 N 877 1971 2848
% row 30.8 69.2 100.0
3 N 818 2079 2897
% row 28.2 71.8 100.0
4 N 840 2742 3582
% row 23.5 76.5 100.0
5 N 612 2410 3022
% row 20.3 79.7 100.0
6 N 483 2360 2843
% row 17.0 83.0 100.0
7 N 369 2986 3355
% row 11.0 89.0 100.0
All N 8783 25642 34425
% row 25.5 74.5 100.0

#Calculate column percentages

table(germany_data$tvtot, germany_data$pdwrk_recode) %>%
  cprop()
##        
##         no    yes   All  
##   0       3.2   4.2   3.8
##   1       3.6   7.6   5.7
##   2       9.2  18.2  13.9
##   3      10.2  17.7  14.1
##   4      14.9  19.8  17.5
##   5      15.1  14.5  14.8
##   6      17.8  10.3  13.9
##   7      26.0   7.7  16.4
##   Total 100.0 100.0 100.0

In this column, we are looking at the correlation of Germans’ paid work status and their TV watching habits throughout the week. Here the data in the ‘yes’ column, row 2 increases drastically the variables in the ‘no’ column of the same row. We could deduce that the probability of people that have paid working status and that watch TV frequently jumps to a high number and continue to climb as the rows increase. However the data in the ‘yes’ column decreases as the variables in the ‘no’ colum increase. this could account for the slow decline we saw in the earlier graph.

see underneath a second percentage column for variable ‘educ’

table(germany_data$tvtot, germany_data$educ_level) %>%
  cprop()
##        
##         BA    No BA All  
##   0       6.1   3.0   3.8
##   1       9.4   4.5   5.7
##   2      18.5  12.5  13.9
##   3      17.3  13.2  14.1
##   4      17.7  17.4  17.5
##   5      12.9  15.3  14.8
##   6      10.2  15.0  13.9
##   7       7.8  19.0  16.4
##   Total 100.0 100.0 100.0

In row 2 all columns jup drastically together. however as the rows continue we see that the people with a bachelors degree start out very stong and then the numbers decrease. this could mean that people with a higher education are less inclined to watch more TV during the week than others who do not have such an education. In comparison to the Pdwrk data we saw above, we could perhaps conclude that people with higher degrees are going to watch less TV than those who are simply going to work everyday. Maybe this is because people who go to work everyday just want to turn their brains off after a long day, but those with a higher education may want to continue their educational pursuits or hobbies.

#Task 5

making conditional column percentages

df <- germany_data %>%
  filter(!is.na(educ_level) & !is.na(tvtot))

df <- df %>%
  mutate(tvtot = case_when(
    tvtot == 1 ~ "Yes",
    tvtot == 0 ~ "No",
    TRUE ~ as.character(tvtot)  # or "Other", or NA_character_, depending on your needs
  ))
table(df$tvtot)
## 
##    2    3    4    5    6    7   No  Yes 
## 2848 2897 3582 3022 2843 3355  768 1162
germany_clean <- germany_data %>%
  filter(!is.na(edulvla) & !is.na(tvtot))

# calculate conditional probabilities
germany_probs <- germany_clean %>%
  count(tvtot, edulvla) %>%
  group_by(edulvla) %>%
  mutate(prob = n / sum(n))
# plot
ggplot(germany_probs, aes(x = as.factor(tvtot), y = prob, color = edulvla)) +
  geom_point() +
  geom_line(aes(group = edulvla)) +
  labs(title = "Conditional Probabilities watching TV",
       subtitle = "by education level",
       x = "Watch scale", 
       y = "Probability") +
  theme_minimal()

In this graph, we see there is a larger increase at point 5 where the education levels and probability both start to increase more drastically. There is a plateau for the light blue line of data, claiming that the higher education value this person has the higher the probability of them watching TV more during the week. This could contradict a conclusion i came to earlier in this assignment. The other lines, those with educational value of 50 and below are less inclined to watch more TV during the week. I would perhaps need to sample a different graph or find another variable to explain this and come to a concrete conclusion later on. What possible theories did you come to about this data?

That’s Homework 5. Hope this helped with introducing you to some potentially new variables and data sets. Good luck with coding!