2 + 2[1] 4
POSC 8410, Week 2
Most of this exercise is setup. The folder you made becomes R’s working directory when you open it in Positron, which is why file paths later in the course work.
The code is to make sure your R set up is working. Put your cursor on the line and hit Cmd/Ctrl + Enter:
2 + 2[1] 4
You should see [1] 4 in the console.
<- assigns a value to a name. Once n_states exists, you can use it to build other objects.
n_states <- 50
n_senators <- n_states * 2
n_senators[1] 100
Notice that assignment is silent (it doesn’t print anything). To see what an object holds, type its name (or look in the Variables pane).
library(tidyverse) goes at the top of the script because read_csv() does not exist until the tidyverse is loaded. Loading a package is once per-session. If you exit your session (close Positron), you’ll need to re-run this stuff.
library(tidyverse)
anes <- read_csv("Data/anes.csv")The path "Data/anes.csv" is a relative path: starting from the class folder you opened, R goes into Data and finds anes.csv. If R says the file does not exist, either you opened the wrong folder in Positron or the file is not actually inside Data.
After running this, anes should appear in the Variables pane with 7,453 rows.
1. What is the mean feeling thermometer toward Trump?
$ pulls a single column out of the data frame, and na.rm = TRUE tells mean() to ignore missing values.
mean(anes$ft_trump, na.rm = TRUE)[1] 38.25805
2. How many rows does the data have?
nrow(anes)[1] 7453
7,453 respondents, one per row.
3. What are the column names?
names(anes) [1] "ID" "state" "attend_online"
[4] "attend_meet" "buttons_signs" "donate"
[7] "contact_congr" "registered" "party"
[10] "vote" "votechoice" "ft_biden"
[13] "ft_trump" "ft_harris" "ft_pence"
[16] "ft_fauci" "ft_scotus" "ft_congress"
[19] "ft_police" "ft_science" "ft_blm"
[22] "limits_campaigns" "limit_imports" "immigration"
[25] "refugees" "act_ineq" "hist_discrim"
[28] "econ_mobility" "tax_rich" "aca"
[31] "vaccines" "reg_emissions" "background_checks"
[34] "freetrade" "minwage"
names() returns the column names as a character vector.
4. What happens without na.rm = TRUE?
mean(anes$ft_trump)[1] NA
You get NA. There are 94 respondents with no value for ft_trump, and one missing value makes the whole mean missing.