Methods, Methods, Methods
Whenever I introduce you to a new method on this module, you will find this section here on the companion. It will contain an RScript for some preliminary data preparation. This is not an actual part of introducing the method, but you are certainly encouraged to read it and to try and understand it.
These sections will work with the American National Election Studies (ANES), and to be more precise with the pilot survey conducted before the 2020 presidential election. You can download the required data set by following this link. The actual data set itself is available here.
Data Prep
Place the ANES data in a folder which you will be using as a working directory for this session. Open the “Code for Data Preparation” below, and copy this into an RScript. Remember to adjust the working directory with the setwd()
command at the beginning. Then run the RScript and you will be ready to proceed to the video.
Code for Data Preparation
######################################
# MMM - Week 1 - Data Preparation
######################################
# Set WD
setwd()
# Load packages
library(tidyverse)
# Load data set
anes <- read_csv("anes.csv")
# Get rid of missing values for variables used in analysis today
## 999 is equivalent to NA, so needs to be recoded
anes$fttrump1 <- with(anes, replace(fttrump1, fttrump1 == 999, NA))
anes <- filter(anes,
!is.na(fttrump1),
!is.na(sex))
# turn support for Trump `fttrump1` into ordered factor with three levels
anes <- anes %>%
mutate(trump=
ordered(
cut(fttrump1, breaks=c(0, 33, 66, 100),
labels=c("low","medium","high"))))
# Label variable `sex`
anes$sex <- factor(anes$sex)
anes <- anes %>%
mutate(sex=
recode(sex,"1"="Male",
"2"="Female"))
# save data set for use in video
write.csv(anes, "anes_week1.csv")
You can copy the code from this page by hovering over the code chunk and clicking the icon in the top-right hand corner. You can then paste it into your RScript.
Video and RScript
You can find the video introducing you to this week’s method by way of a worked example below. You can also access the code I am typing up in the video in the “Code for Data Analysis” section. I would encourage you to type it yourself, though, as then code tends to better sink into the depths of your brain 😉
Code for Data Analysis
######################################
# MMM - Week 1 - Crosstabulations
######################################
# Set WD
setwd()
# Load packages
library(tidyverse)
# Load data set
anes <- read_csv("anes_week1.csv")
anes$sex <- as.factor(anes$sex)
anes$trump <- as.factor(anes$trump)
# Tabulate relationship between sex and support for Trump
table(anes$sex,anes$trump)
prop.table(table(anes$sex,anes$trump))
prop.table(table(anes$sex,anes$trump), margin = 1)
# save table for analysis
trumpsex <- table(anes$sex,anes$trump)
trumpsex
xsq <- chisq.test(trumpsex, correct=FALSE)
xsq
# display observed and expected values
xsq$expected
xsq$observed
Cross Tabulations in R