This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.
When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
summary(cars)
## speed dist
## Min. : 4.0 Min. : 2.00
## 1st Qu.:12.0 1st Qu.: 26.00
## Median :15.0 Median : 36.00
## Mean :15.4 Mean : 42.98
## 3rd Qu.:19.0 3rd Qu.: 56.00
## Max. :25.0 Max. :120.00
You can also embed plots, for example:
Note that the echo = FALSE parameter was added to the
code chunk to prevent printing of the R code that generated the
plot.
# 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.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
## Warning: package 'fst' was built under R version 4.3.2
## Warning: package 'modelsummary' was built under R version 4.3.2
## Version 2.0.0 of `modelsummary`, to be released soon, will introduce a
## breaking change: The default table-drawing package will be `tinytable`
## instead of `kableExtra`. All currently supported table-drawing packages
## will continue to be supported for the foreseeable future, including
## `kableExtra`, `gt`, `huxtable`, `flextable, and `DT`.
##
## You can always call the `config_modelsummary()` function to change the
## default table-drawing package in persistent fashion. To try `tinytable`
## now:
##
## config_modelsummary(factory_default = 'tinytable')
##
## To set the default back to `kableExtra`:
##
## config_modelsummary(factory_default = 'kableExtra')
## [[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"
getwd()
## [1] "C:/Users/hassa947/Desktop"
ess <- read_fst("All-ESS-Data.fst")
## Warning: package 'fstcore' was built under R version 4.3.2
unique(ess$cntry)
## [1] "AT" "BE" "CH" "CZ" "DE" "DK" "ES" "FI" "FR" "GB" "GR" "HU" "IE" "IL" "IT"
## [16] "LU" "NL" "NO" "PL" "PT" "SE" "SI" "EE" "IS" "SK" "TR" "UA" "BG" "CY" "RU"
## [31] "HR" "LV" "RO" "LT" "AL" "XK" "ME" "RS" "MK"
#Task 1 #Prompt and question: calculate the average for the variable ‘health’ for the countries of Serbia and Belgium. On average, based on the ESS data, who reports higher levels of subjective health: Serbia and Belgium?
Subsetting for Belgium
Belgium_health <- ess %>%
filter(cntry == "BE") %>%
select(health)
Belgium_health$y <- Belgium_health$health
table(Belgium_health$y)
##
## 1 2 3 4 5 7 8 9
## 4033 9262 3338 674 137 2 3 2
Calculating mean (avergae) of health for Belgium
mean_y <- mean(Belgium_health$y, na.rm = TRUE)
cat("Mean of 'y' is:", mean_y, "\n")
## Mean of 'y' is: 2.063377
Subsetting for Serbia
serbia_health <- ess %>%
filter(cntry == "RS") %>%
select(health)
serbia_health$y <- serbia_health$health
table(serbia_health$y)
##
## 1 2 3 4 5 8 9
## 620 1051 1332 411 107 3 24
Calculating mean (avergae) of health for Serbia
mean_y <- mean(serbia_health$y, na.rm = TRUE)
cat("Mean of 'y' is:", mean_y, "\n")
## Mean of 'y' is: 2.575254
#Answer: Based on the ESS data, Serbia reports higher levels of health. The average for Belgium is 2.063377 and for Serbia it is 2.575254, therefore Serbia reports higher levels of subjective health
#Task 2 #Prompt and question: what is the most common category selected, for Norwegian respondents, for how often they socially meet with friends or relatives. The variable of interest is: sclmeet.
Counting Categorical Variables
norway_meetfrc <- ess %>%
filter(cntry == "NO") %>%
select(sclmeet)
norway_meetfrc$y <- norway_meetfrc$sclmeet
table(norway_meetfrc$y)
##
## 1 2 3 4 5 6 7 77 88
## 44 356 746 2569 2119 5764 4458 2 7
norway_meetfrc$y[norway_meetfrc$y %in% 6:8] <- NA
Calculating mean and median
mean_y <- mean(norway_meetfrc$y, na.rm = TRUE)
median_y <- median(norway_meetfrc$y, na.rm = TRUE)
cat("Mean of 'y':", mean_y, "\n")
## Mean of 'y': 4.216156
cat("Median of 'y':", median_y, "\n")
## Median of 'y': 4
Convertying to categories
df <- norway_meetfrc %>%
mutate(
y_category = case_when(
y == 1 ~ "Never",
y == 2 ~ "Less than once a month",
y == 3 ~ "Once a month",
y == 4 ~ "Several times a month",
y == 5 ~ "Once a week",
y == 6 ~ "Several times a week",
y == 7 ~ "Everyday",
TRUE ~ NA_character_
),
y_category = fct_relevel(factor(y_category), ### here you would put the categories in order you want them to appear or else it will appear alphabetically
"Never",
"Less than once a month",
"once a month",
"Several times a month",
"once a week",
"Several times a week",
"Everyday")
)
## Warning: There was 1 warning in `mutate()`.
## ℹ In argument: `y_category = fct_relevel(...)`.
## Caused by warning:
## ! 4 unknown levels in `f`: once a month, once a week, Several times a week, and
## Everyday
table(df$y_category)
##
## Never Less than once a month Several times a month
## 44 356 2569
## Once a month Once a week
## 746 2119
get_mode <- function(v) {
tbl <- table(v)
mode_vals <- as.character(names(tbl)[tbl == max(tbl)])
return(mode_vals)
}
mode_values <- get_mode(df$y_category)
cat("Mode of y category:", paste(mode_values, collapse = ", "), "\n")
## Mode of y category: Several times a month
#Answer: The most common category category selected for Norwegian respondents, for how often they socially meet with friends or relatives is “Several times a month”
#Task 3 #Prompt and question: when you use the summary() function for the variable wrclmch (i.e., how worried about climate change) for both the countries of Estonia and Portugal – 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.
Comparing means with groupby
result <- ess %>%
filter(cntry %in% c("EE", "PT")) %>%
mutate(wrclmch = recode(wrclmch , `77` = NA_real_, `88` = NA_real_, `99` = NA_real_)) %>%
group_by(cntry) %>%
summarize(mean_wrclmch = mean(wrclmch , na.rm = TRUE))
print(result)
## # A tibble: 2 × 2
## cntry mean_wrclmch
## <chr> <dbl>
## 1 EE 2.86
## 2 PT 3.58
estonia_data <- filter(ess, cntry == "EE")
portugal_data <- filter(ess, cntry == "PT")
summary_estonia <- summary(estonia_data$wrclmch)
summary_portugal <- summary(portugal_data$wrclmch)
print(summary(estonia_data$wrclmch))
## Min. 1st Qu. Median Mean 3rd Qu. Max. NA's
## 1.000 2.000 3.000 2.855 3.000 8.000 13295
print(summary(portugal_data$wrclmch))
## Min. 1st Qu. Median Mean 3rd Qu. Max. NA's
## 1.000 3.000 4.000 3.583 4.000 8.000 14773
#Answer: When I use the summary() function for wrclmh for Estonia and Portugal, I notice a lot of difference between the two countries. For Estonia the 1st qu. is at 2 while for Portugal it is 3. Additionally, the mean and medians are also different. for Estonia the mean is 2.855 and median is at 3, while for Portugal the mean is at 3.583 and the median is at 4. Lastly, the 3rd qu. for Estonia is at 3 while for Portugal it is at 4. By comparing these numbers, I can tell that almost in all the calculations between the two countries, Portugal seems to be 1.0 higher than Estonia, showing us that they are more worried about climate change.
#Task 4 #Prompt and question: using the variables stfhlth and gndr, answer the following: on average, who is more sastified with health services in Italy, men or women? Explain while referring to the output generated.
Average of Y by X
italy_data <- ess %>%
filter(cntry == "IT")
italy_data <- italy_data %>%
mutate(
gndr = case_when(
gndr == 1 ~ "Male",
gndr == 2 ~ "Female",
TRUE ~ as.character(gndr)
),
stfhlth = ifelse(stfhlth %in% c(77, 88), NA, stfhlth )
)
mean_male_stfhlth <- italy_data %>%
filter(gndr == "Male") %>%
summarize(mean_stfhlth_men = mean(stfhlth, na.rm = TRUE))
print(mean_male_stfhlth)
## mean_stfhlth_men
## 1 5.558534
mean_female_stfhlth <- italy_data %>%
filter(gndr == "Female") %>%
summarize(mean_stfhlth_women = mean(stfhlth, na.rm = TRUE))
print(mean_female_stfhlth)
## mean_stfhlth_women
## 1 5.420372
means_by_gender <- italy_data %>%
group_by(gndr) %>%
summarize(stfhlth = mean(stfhlth, na.rm = TRUE))
print(means_by_gender)
## # A tibble: 3 × 2
## gndr stfhlth
## <chr> <dbl>
## 1 9 4
## 2 Female 5.42
## 3 Male 5.56
#Answer: On average, Men are more satisfied with health services in Italy. For women the average of satisfaction is 5.42 and for men it is 5.56, therefore, while there is not a big difference, men are more satisfied with health services in Italy.
#Task 5 #Create boxplots, in the same graph, for stfdem and stfgov for the country of France. Provide an appropriate title and labels. Further, tell us: according to ESS data, would we say that the median French person is more satisfied with the democracy or the national government? Explain
france_data <- ess %>%
filter(cntry == "FR")
france_data %>%
mutate(stfdem = ifelse(stfdem %in% c(77, 88, 99), NA, stfdem),
stfgov = ifelse(stfgov %in% c(77, 88, 99), NA, stfgov)) %>%
select(stfdem, stfgov) %>%
gather(variable, value, c(stfdem, stfgov)) %>%
ggplot(aes(x = variable, y = value)) +
geom_boxplot() +
labs(y = "Satisfaction (0-10)", x = "X-axis", title = "Boxplot of satisfaction with the way democracy works vs. the national government") +
theme_minimal()
## Warning: Removed 557 rows containing non-finite values (`stat_boxplot()`).
#Answer: According to the ESS data, the median French person is more satisfied with the way democracy works rather than the national government. The median for democracy is at 5.0 while for the national government it is at approximately 4.0. Overall the satisfaction for the way national government works is less than democracy because the 1st qu. and 3rd qu. are also lower for national government. In conclusion, the median French person is more satisfied with the way democracy works.