In the list following c(, you would be any package you need in between quotation marks.
# List of packages
packages <- c("tidyverse", "fst", "modelsummary") # 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.4 ✔ readr 2.1.5
## ✔ forcats 1.0.0 ✔ stringr 1.5.1
## ✔ ggplot2 3.4.4 ✔ tibble 3.2.1
## ✔ lubridate 1.9.3 ✔ 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
## [[1]]
## [1] "lubridate" "forcats" "stringr" "dplyr" "purrr" "readr"
## [7] "tidyr" "tibble" "ggplot2" "tidyverse" "stats" "graphics"
## [13] "grDevices" "utils" "datasets" "methods" "base"
##
## [[2]]
## [1] "fst" "lubridate" "forcats" "stringr" "dplyr" "purrr"
## [7] "readr" "tidyr" "tibble" "ggplot2" "tidyverse" "stats"
## [13] "graphics" "grDevices" "utils" "datasets" "methods" "base"
##
## [[3]]
## [1] "modelsummary" "fst" "lubridate" "forcats" "stringr"
## [6] "dplyr" "purrr" "readr" "tidyr" "tibble"
## [11] "ggplot2" "tidyverse" "stats" "graphics" "grDevices"
## [16] "utils" "datasets" "methods" "base"
Let’s load our data, fst style. Remember the data needs to be in the folder where you’re working from. You can enter getwd() to check your working directory.
ess <- read_fst("All-ESS-Data.fst")
If you struggle to load the entire ESS dataset on your device (e.g., you get a memory error code), you can individually load the country datasets below after downloading them from the course website. Otherwise, skip this step and jump to “Subsetting”.
Remove hashtags and run the following commands to read each country dataset as specified below.
For both the homework and tutorial, you will need:
#belgium_data <- read.fst("belgium_data.fst")
#estonia_data <- read.fst("estonia_data.fst")
#france_data <- read.fst("france_data.fst")
#norway_data <- read.fst("norway_data.fst")
#ireland_data <- read.fst("ireland_data.fst")
#portugal_data <- read.fst("portugal_data.fst")
#serbia_data <- read.fst("serbia_data.fst")
#italy_data <- read.fst("italy_data.fst")
Take note of this last visual as you will need to interpret it for the homework.
End of Tutorial - See you next week!
Instructions: Start a new R markdown for the homework and call it “Yourlastname_Firstname_Homework_1”.
Copy everything below from Task 1 to Task 5. Keep the task prompt and questions, and provide your code and answer underneath.
To generate a new code box, click on the +C sign above. Underneath your code, provide your answer to the task question.
When you are done, click on “Knit” above, then “Knit to Html”. Wait for everything to compile. If you get an error like “Execution halted”, it means there are issues with your code you must fix. When all issues are fixed, it will prompt a new window. Then click on “Publish” in the top right, and then Rpubs (the first option) and follow the instructions to create your Rpubs account and get your Rpubs link for your document (i.e., html link as I provide for the tutorial).
Note: Make sure to provide both your markdown file and R pubs link. If you do not submit both, you will be penalized 2 pts. out of the 5 pts. total.
Provide code and answer.
Prompt and question: calculate the average for the variable ‘happy’ for the country of Norway. On average, based on the ESS data, who reports higher levels of happiness: Norway or Belgium?
Note: we already did it for Belgium. You just need to compare to Norway’s average, making sure to provide the code for both.
Belgium Happiness code TASK 1
#EXPLANATION TASK 1: We are currently filtering the country Belgium and selecting the variable happiness
belgium_happy <- ess %>% # note: if you work from belgium_data replace "ess" with belgium_data
filter(cntry == "BE") %>%
select(happy)
#EXPLANATION TASK 1: We then remove invalid categories from 77 to 99 since these responses are designated as “NA” or are invalid answers that will conflict with our results if considered.We display the table to make sure our numbers are correct.
belgium_happy$y <- belgium_happy$happy
# need to remove 77, 88, 99 or else will alter results. See data portal for what they represent (e.g. DK, Refusal, etc.)
# Recode values 77 through 99 to NA
belgium_happy$y[belgium_happy$y %in% 77:99] <- NA
# checking again
table(belgium_happy$y)
##
## 0 1 2 3 4 5 6 7 8 9 10
## 50 27 104 194 234 830 999 3503 6521 3402 1565
#EXPLANATION TASK 1: We then calculate the mean of the happiness numbers and designated it out of 10 to display an average happiness within the Belgium.
mean_belgium <- mean(belgium_happy$y, na.rm = TRUE)
cat("The average Belgium happiness is:", mean_belgium, "out of 10")
## The average Belgium happiness is: 7.737334 out of 10
#Norway Happiness code TASK 1
#EXPLANATION TASK 1: We are currently filtering the country Norway and selecting the variable happiness
norway_happy <- ess %>% # note: if you work from belgium_data replace "ess" with belgium_data
filter(cntry == "NO") %>%
select(happy)
#EXPLANATION TASK 1: We then remove invalid categories from 77 to 99 since these responses are designated as “NA” or are invalid answers that will conflict with our results if considered. We display the table to make sure our numbers are correct.
norway_happy$y <- norway_happy$happy
# need to remove 77, 88, 99 or else will alter results. See data portal for what they represent (e.g. DK, Refusal, etc.)
# Recode values 77 through 99 to NA
norway_happy$y[norway_happy$y %in% 77:99] <- NA
# checking again
table(norway_happy$y)
##
## 0 1 2 3 4 5 6 7 8 9 10
## 15 29 59 163 238 730 817 2617 5235 3796 2344
#EXPLANATION TASK 1: We then calculate the mean of the happiness numbers and designated it out of 10 to display an average happiness within the Norway.
mean_norway <- mean(norway_happy$y, na.rm = TRUE)
cat("The average Norway happiness is:", mean_norway, "out of 10")
## The average Norway happiness is: 7.975005 out of 10
#ANSWER TASK 1
As we can see, according to what has been displayed, Belgium has a 7.73 happiness rating out of 10, whilst Norway has a 7.97 happiness rating out of 10. Through these numbers, we can affectivly designate Norway as being a happier country on average than Belgium.
Provide code and answer.
Prompt and question: what is the most common category selected, for Irish respondents, for frequency of binge drinking? The variable of interest is: alcbnge.
More info here: https://ess-search.nsd.no/en/variable/0c65116e-7481-4ca6-b1d9-f237db99a694.
Hint: need to convert numeric value entries to categories as specified in the variable information link. We did similar steps for Estonia and the climate change attitude variable.
EXPLANATION TASK 2: For our first chunk, we are filtering the country Ireland through its binge drinking levels, therefore we must select the Ireland database and select alcbnge as its specific categories.
According to the ess link, the categories only span from 1 - 5, so we will remove categories 6 to 8 since they provide NA/invalid answers.
ireland_binge <- ess %>%
filter(cntry == "IE") %>%
select(alcbnge)
##Excludes invalid responses
ireland_binge$alcbnge[ireland_binge$alcbnge%in% 6:8] <- NA
EXPLANATION TASK 2: After running the code above, we will designate the categories with their respective names taken from the website.
# Converting numeric values to categories
ireland_binge <- ireland_binge %>%
mutate(
alcbnge_category = case_when(
alcbnge == 1 ~ "Daily",
alcbnge == 2 ~ "Weekly",
alcbnge == 3 ~ "Monthly",
alcbnge == 4 ~ "Less than Monthly",
alcbnge == 5 ~ "Never",
TRUE ~ NA_character_
),
alcbnge_category = fct_relevel(factor(alcbnge_category),
"Daily",
"Weekly",
"Monthly",
"Less than Monthly",
"Never")
)
# Displays information
table(ireland_binge$alcbnge_category)
##
## Daily Weekly Monthly Less than Monthly
## 65 650 346 417
## Never
## 239
ANSWER TASK 2
As we can see, according to the table, Irish people most commonly drink alcohol on a weekly basis, having had 650 votes in this category.
Provide code and answer.
Prompt and question: when you use the summary() function for the variable plnftr (about planning for future or taking every each day as it comes from 0-10) for both the countries of Portugal and Serbia, what do you notice? What stands out as different when you compare the two countries (note: look up the variable information on the ESS website to help with interpretation)? Explain while referring to the output generated.
#EXPLANATION TASK 3: Filtering the country Portugal and displaying on a scale of 0 to 10 if people plan for the future. We then display all that information in a summary which will display the Min/0, 1st quartile, median, mean, 3rd quartile, Max. and NA’S of statistics for people who plan for the future.
portugal_plnftr <- ess %>%
filter(cntry == "PT") %>%
select(plnftr)
portugal_plnftr$y <- portugal_plnftr$plnftr
# need to remove 77, 88, 99 or else will alter results. See data portal for what they represent (e.g. DK, Refusal, etc.)
# Recode values 77 through 99 to NA
portugal_plnftr$y[portugal_plnftr$plnftr %in% 77:99] <- NA
summary(portugal_plnftr$y)
## Min. 1st Qu. Median Mean 3rd Qu. Max. NA's
## 0.000 3.000 5.000 5.418 8.000 10.000 14644
#EXPLANATION TASK 3: Filtering the country Serbia and displaying on a scale of 0 to 10 if people plan for the future. We then display all that information in a summary which will display the Min/0, 1st quartile, median, mean, 3rd quartile, Max. and NA’S of statistics for people who plan for the future.
serbia_plnftr <- ess %>%
filter(cntry == "RS") %>%
select(plnftr)
serbia_plnftr$y <- serbia_plnftr$plnftr
# need to remove 77, 88, 99 or else will alter results. See data portal for what they represent (e.g. DK, Refusal, etc.)
# Recode values 77 through 99 to NA
serbia_plnftr$y[serbia_plnftr$plnftr %in% 77:99] <- NA
summary(serbia_plnftr$y)
## Min. 1st Qu. Median Mean 3rd Qu. Max. NA's
## 0.000 0.000 4.000 4.143 8.000 10.000 1526
#ANSWER TASK 3
Based on the information provided to us, we can conclude that Portugal’s population has a stronger tendency to plan for the future in comparison to Serbia’s. This can be seen in their averages, as Portugal’s average has a rating of 5.4, whilst Serbia only has an average rating of 4.1. However, among the upper quartile of both countries, the population are way more inclined to plan for their future, having a rating of 8.0 in both countries. The difference in average could have been inflicted due to the countries population in different quartiles among the data.
Provide code and answer.
Prompt and question: using the variables stfdem and gndr, answer the following: on average, who is more dissastified with democracy in Italy, men or women? Explain while referring to the output generated.
Info on variable here: https://ess.sikt.no/en/variable/query/stfdem/page/1
#EXPLANATION TASK 4: We first need filter the countries by choosing Italy, and select both satisfaction with democracy and gender in association. We then filter out all invalid answers, and change the categorial names of one and two to their respective genders as listed on the ESS website, one = male and two = female. We then display the table to see the data.
italy_democracy <- ess %>%
filter(cntry == "IT") %>%
select(stfdem, gndr)
# need to remove 77, 88, 99 or else will alter results. See data portal for what they represent (e.g. DK, Refusal, etc.)
# Recode values 77 through 99 to NA
italy_democracy$stfdem[italy_democracy$stfdem %in% c(77, 88, 99)] <- NA
italy_democracy$gndr[italy_democracy$gndr %in% c(77, 88, 99)] <- NA
# Converting numeric values to categories
italy_democracy <- italy_democracy %>%
mutate(
gndr = case_when(
gndr == 1 ~ "Male",
gndr == 2 ~ "Female",
TRUE ~ NA_character_
)
)
table(italy_democracy)
## gndr
## stfdem Female Male
## 0 382 328
## 1 186 179
## 2 376 355
## 3 518 440
## 4 671 549
## 5 956 829
## 6 884 838
## 7 628 671
## 8 370 363
## 9 67 71
## 10 46 56
#EXPLANATION TASK 4: We then take the data and group them through gender and run a piece of code that allows us to calculate the mean from both geneders, we then print the results.
satis_gender <- italy_democracy %>%
#Compute mean by gender
group_by(gndr) %>%
summarize(average_satisfaction = mean(stfdem, na.rm = TRUE))
#display results
print(satis_gender)
## # A tibble: 3 × 2
## gndr average_satisfaction
## <chr> <dbl>
## 1 Female 4.66
## 2 Male 4.78
## 3 <NA> 3.25
#ANSWER TASK 4
After analysis of the data, we can see that both genders of the Italian population show moderate levels of satisfaction with their governments democracy. But on average, the female population seems to display more dissatisfaction of Italian democracy, having a rating of 4.6 out of 10, in comparison to men which has a rating of 4.7 out of 10. The female average in satisfaction with Italian democracy is lower by the male average by only 0.1 points.
Provide code and answer.
Prompt: Interpret the boxplot graph of stfedu and stfhlth that we generated already: according to ESS data, would we say that the median French person is more satisfied with the education system or health services? Explain.
Change the boxplot graph: provide the code to change some of the key labels: (1) Change the title to: Boxplot of satisfaction with the state of education vs. health services; (2) Remove the x-axis label; (3) Change the y-axis label to: Satisfaction (0-10).
Hint: copy the boxplot code above and just replace or cut what is asked.
#EXPLANATION TASK 5: In this section we have changed the title, remove the x axis label, and change the y axis label title.
The two variables are about satisfaction with the state of education and health services.
france_data <- ess %>%
filter(cntry == "FR")
france_data %>%
# Setting values to NA
mutate(stfedu = ifelse(stfedu %in% c(77, 88, 99), NA, stfedu),
stfhlth = ifelse(stfhlth %in% c(77, 88, 99), NA, stfhlth)) %>%
# Reshaping the data
select(stfedu, stfhlth) %>%
gather(variable, value, c(stfedu, stfhlth)) %>%
# Creating the boxplot
ggplot(aes(x = variable, y = value)) +
geom_boxplot() +
labs(y = "Satisfaction (0-10)", x = "", title = "Satisfaction with the State of Education Vs. Health Services") +
theme_minimal()
## Warning: Removed 364 rows containing non-finite values (`stat_boxplot()`).
#ANSWER TASK 5
Through analysing this boxplot, we can determine that the French person is more satisfied with the countries health system than the countries education system.This can distinguished through looking at the median lines of each box, for education the median is around 5.0 out of 10 in satisfaction whilst the median in health services is 7.3 to 7.4.