Skip to content

Instantly share code, notes, and snippets.

@vanatteveldt
Created November 30, 2022 13:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vanatteveldt/dc206a9e52a069c78863332fd6596a0f to your computer and use it in GitHub Desktop.
Save vanatteveldt/dc206a9e52a069c78863332fd6596a0f to your computer and use it in GitHub Desktop.
library(tidyverse)
elections = tribble(
~year,~state_po,~party_Detailed,~candidatevotes,~totalvotes,
1976,"AL","DEMOCRAT",500,1000,
1976,"AL","REPUBLICAN",450,1000,
1976,"AL","x",30,1000,
1976,"AL","x",10,1000,
1976,"AL","x",7,1000,
1976,"AL","x",2,1000,
1976,"AL","x",1,1000,
1976,"AK","REPUBLICAN",70,100,
1976,"AK","DEMOCRAT",20,100,
1976,"AK","x",10,100,
)
# Question 7:
# Consider again the elections data set shown on the previous page.
# We would like to compute the vote share of each of the two major parties
# in each year and state, e.g. the votes for that party in that state in that year,
# divided by the total number of votes for both parties in that state.
# Which of the following lines of code achieves this goal?
# Option B, i.e. the answer initially marked as 'incorrect'
filter(elections, party_Detailed %in% c("DEMOCRAT", "REPUBLICAN")) |>
group_by(year, state_po) |>
summarize(share=candidatevotes / sum(candidatevotes))
# Option D, i.e. the answer initially marked as 'incorrect'
filter(elections, party_Detailed %in% c("DEMOCRAT", "REPUBLICAN")) |>
group_by(year, state_po) |>
mutate(share=candidatevotes / sum(candidatevotes))
# A tibble: 4 × 3
# Groups: year, state_po [2]
year state_po share
<dbl> <chr> <dbl>
1 1976 AK 0.778
2 1976 AK 0.222
3 1976 AL 0.526
4 1976 AL 0.474
# A tibble: 4 × 6
# Groups: year, state_po [2]
year state_po party_Detailed candidatevotes totalvotes share
<dbl> <chr> <chr> <dbl> <dbl> <dbl>
1 1976 AL DEMOCRAT 500 1000 0.526
2 1976 AL REPUBLICAN 450 1000 0.474
3 1976 AK REPUBLICAN 70 100 0.778
4 1976 AK DEMOCRAT 20 100 0.222
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment