Create a new working directory by starting a new R project. Go to ‘File’, then ‘New Project’, then ‘New Directory’. Provide a name for your directory: e.g., “SOC_252_Project”.
Go to the top again to ‘File’, then new file, then do R markdown and save it as “Participation_3_yourlastname”. Go find your new directory, open it to confirm that you have your .Rproj file, and your .Rmd file.
Setting up the Environment.
# List of packages
packages <- c("tidyverse", "modelsummary", "forcats", "RColorBrewer",
"fst", "viridis", "knitr", "kableExtra", "rmarkdown", "ggridges", "viridis", "questionr") # 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
## 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"
Copy-paste the class dataset (wherever it is located on your computer) into your current project directory. It will be useful if you also download Rmd from tutorials.
Load class dataset.
ess <- read_fst("All-ESS-Data.fst")
Note: if you get a message like OpenMp was not detected, it is fine. As long as you see the dataset loaded in the top right window, you are golden.
Move your mouse near the Run symbol where you see a plus sign with a C. Click on it, then on R.
You will see a a grey bar appear with the following symbol at the top: ```{r}
In there copy the following and run it by clicking the green play button that is at the extreme right of the box:
print(“hell yeah this works!”)
Everything that is in that box is R code. Everything outside is text.
You can test a code chunk by clicking the run button as we just did. If it does not work, it will give you an error code. You cannot “Knit” if there are errors in parts of your code. So make sure to test chunk by chunk. A common error also is to work on your markdown for some time, have referenced objects that are in your environment, but in the markdown sequence are “called upon” before you create the object (or altogether forgot that part). For example, you renamed “France_data” as “df” in your environment but forgot to put that part in your code. When you go to knit, it will not work and it will indicate on what “line” (so where in your code) produced the error.
Want to see what it looks like?
Add some text here.
Some with two hashtags (for titles)
Or just straight typing. Anything you would like.
When you are ready: Go to knit, then click knit to html.
Wait, it will take some time. If it works, it will open a new window and you can click publish and create an account to be able to post html docs online for free.
For Participation 3, you must post both your markdown file and an html link to your markdown on the discussion board “Participation 3”.
The following are a series of missions. You DO NOT need to complete them all to receive your marks. The goal is to complete as many as you can and to create the markdown file + html as a fundamental skill moving forward.
Note that some of these will be directly useful to your next stepping stone.
Israel_data <- ess[ess$cntry == "IL", ]
table(Israel_data$happy) ##table(data$variable)
##
## 0 1 2 3 4 5 6 7 8 9 10 77 88 99
## 104 93 199 339 475 1312 1289 2456 4212 2785 2693 14 143 104
##Create tables between ess and variables of interest. Take note of what you need to clean (i.e., the 7, 8, 9, and 77, 88, 99).
Look into an additional socio-demographic variable (other than the 5 covered in the tutorial), create a table and take note of how to clean it. You can do more than one, but do at least one for the mission.
Provide the ess data portal link here. For example, like so:
https://ess-search.nsd.no/en/variable/32558258-72b1-479b-8cca-49c9d569408d
Take note of the categories and consider how to recode them (using mutate) so as to create fewer categories (if needed) that are meaningful for analytical purposes. For example, for the one above you can consider recoding 1, 2, and 5 together, 3 and 4 together, and 6 separately.
Filter to your country of interest and use mutate to clean your variables. If you want, you can “select” all your variables of interest now, including the socio-demographic ones.
Note: whenever you recode or clean, always double check what you did by comparing pre and post. So, for example, if you tried to clean and named your dataset france_clean from the uncleaned france_data, do tables of variables of interest between the two to see if the recodes and cleaning worked as intended.
##There are many ways to mutate unneccesary variables/categories. Here, I will use "data$variable[data$variable %in% c(77,88,99)] <- NA
Israel_data$happy[Israel_data$happy %in% c(77, 88, 99)] <- NA
table(Israel_data$happy)
##
## 0 1 2 3 4 5 6 7 8 9 10
## 104 93 199 339 475 1312 1289 2456 4212 2785 2693
##make sure doing this to every variables I am going to use.
Do a datasummary_skim of variables of interest. You can select variables as follows:
# datasummary_skim(dataset %>% select(v1, v2, v3))
datasummary_skim(Israel_data %>% select(eduail1,happy,hinctnta))
| Unique (#) | Missing (%) | Mean | SD | Min | Median | Max | ||
|---|---|---|---|---|---|---|---|---|
| eduail1 | 22 | 69 | 307.9 | 1164.1 | 1.0 | 7.0 | 8888.0 | |
| happy | 12 | 2 | 7.6 | 2.0 | 0.0 | 8.0 | 10.0 | |
| hinctnta | 14 | 15 | 26.8 | 35.3 | 1.0 | 6.0 | 99.0 |
Note: code here and below, you just need to replace with what you need and remove the hashtags.
Do a quick frequency check for socio-demographics of interest, then visualize. Here’s an example for geo:
#freq(filtered_data$geo)
#filtered_data %>%
# drop_na(geo) %>%
# select(geo) %>%
# freq() %>%
# as.data.frame() %>%
# ggplot(aes(x=factor(rownames(.),
# levels= c("Urban",
# "Peri-Urban",
# "Rural")),
# y=`%`)) +
# geom_col() +
# labs(title = "Distribution of Place of Residence",
# x = "Geo")
Depending on what you look into, you will note that some of the percentage seem off relative to what it would be for the entire population. For example, % rural in the sample vs. % rural in the population. That is why we eventually need to make adjustments and apply survey weights. We will talk more about the specific survey design of the ESS in future lectures.
So let’s turn to do conditional probabilities, giving us a better sense of what’s going conditional on a specific category (i.e., dividing by say where someone lives rather than by the total).
Do column percentages (as conditional %) with cprop(). Here’s an example:
#table(france_data$clsprty, france_data$educ_level) %>%
# cprop()
You can also do row percentages with rprop().
Do cross tabs (especially useful for exploring relationships between categorical variables). Here’s an example we saw:
# clsprtyedu <- datasummary_crosstab(clsprty ~ educ_level, data = france_data)
# clsprtyedu
Note: you can do it for a continuous/discrete variable, but the table will yield column percentages for each of the values for a column (for example, for stfdem, all of 0 to 10).
Produce a visual for how a categorical of interest is distributed over time.
For year example:
#table(filtered_data$educ_level, filtered_data$year) %>%
# cprop() %>%
# as.data.frame() %>%
# filter(Var1 != "Total",
# Var2 != "All") %>%
# ggplot(aes(x=Var2 %>% as.character() %>% as.integer(),
# y=Freq,
# color=Var1)) +
# geom_line() +
# labs(title="Educational levels by Survey Year",
# x = "Survey",
# color = "Education")
For birth year example:
#table(filtered_data$educ_level, filtered_data$year) %>%
# cprop() %>%
# as.data.frame() %>%
# filter(Var1 != "Total",
# Var2 != "All") %>%
# ggplot(aes(x=Var2 %>% as.character() %>% as.integer(),
# y=Freq,
# color=Var1)) +
# geom_line() +
# labs(title="Educational levels by Birth Year",
# x = "Birth Year",
# color = "Education")
Do a visualization between a categorical variable and an outcome of interest. You can play around with geom(). Focus on computing as average.
Do a second visualization between the same categorical variable and an outcome of interest. Focus this time on computing conditional probabilities or percentages.
Here are two code examples:
# double check clean
#france_data <- france_data %>%
# filter(!is.na(educ_level) & !is.na(clsprty))
# visualize
#table(france_data$clsprty, france_data$educ_level) %>%
# cprop() %>%
#as.data.frame() %>%
#filter(Var1 != "Total",
# Var2 != "All") %>%
#ggplot(aes(x=Var1, y=Freq, fill=Var2)) +
#geom_col(position = "dodge") +
#labs(title="Feeling close to a particular party in France",
# x = "Feeling close (Y/N)",
# fill = "At least BA vs. Not")
# double check clean
#france_clean <- france_data %>%
# filter(!is.na(geo) & !is.na(trstplt))
# calculate conditional probabilities
#france_probs <- france_clean %>%
# count(trstplt, geo) %>%
# group_by(geo) %>%
# mutate(prob = n / sum(n))
# plot
#ggplot(france_probs, aes(x = as.factor(trstplt), y = prob, color = geo)) +
# geom_point() +
# geom_line(aes(group = geo)) +
# labs(title = "Conditional Probabilities of Trust in Politicians",
# subtitle = "by Place of Residence",
# x = "Trust Scale",
# y = "Probability") +
#theme_minimal()
Shifting to your outcome of interest, produce a visualization for the average by survey year, as we did in the last tutorial.
Change the ylim, to ‘Zoom in’ and see more of the fluctuations from year to year. You can play around with annotating, or adding text, etc. if you wish.
Compare your mean(outcome) to the ESS baseline (all, inclusive of your country).
Compare the overall average for your outcome (i.e., not by survey year), relative to all other countries. Just as we did in Tutorial 2, with geom_point and geom_text, where each point had an associated two-letter country code.
Do the same for a different outcome of interest, but compare to specific countries (at least 2) instead of the ESS baseline.
Produce a distribution of your outcome by survey year using geom_density_ridges(), as we did in the last tutorial.
Now produce a visual for the average by year of birth, for your outcome of interest.
Now do a geom_smooth() and geom_point(), as we did in the last tutorial.
Produce a last visual of choice. Anything you would like. Experiment, be colorful, or keep it minimalist.
Turn all your variables into numeric ones, including your categorical variables (as they were previously coded). A quick way is to filter and select from the ess and rename your dataset to a new name, say df_corr.
We will use the datasummary_correlation function, which identifies all the numeric variables, and calculates the correlation between each of those variables
Very important: select only 10 variables you want to look into! Make sure it is a subset and not all 2000+ variables.
# datasummary_correlation(subsetdata)