df2 <- structure(list(location = c("Dayton", "Toledo"), total_voters = c(236L,
332L), candidate_1 = c(49L, 61L), candidate_2 = c(33L, 78L),
candidate_3 = c(19L, 71L), candidate_5 = c(42L, 52L)), row.names = c(NA,
-2L), class = "data.frame")
I have data coming from a SQL query that is shaped as such:
+----------+--------------+-------------+-------------+-------------+-------------+-------------+
| location | total_voters | candidate_1 | candidate_2 | candidate_3 | candidate_4 | candidate_5 |
+----------+--------------+-------------+-------------+-------------+-------------+-------------+
| Dayton | 236 | 49 | 33 | 19 | 93 | 42 |
| Toledo | 332 | 61 | 78 | 71 | 70 | 52 |
+----------+--------------+-------------+-------------+-------------+-------------+-------------+
The numbers represent the number of votes for each candidate. So what am I trying to do? I'd like to use R (I imagine through either dplyr or tidyr) to pivot this data so it looks as such:
+-------------+-------+----------+--------------+
| candidate | votes | location | total_voters |
+-------------+-------+----------+--------------+
| candidate_1 | 49 | Dayton | 236 |
| candidate_2 | 33 | Dayton | 236 |
| candidate_3 | 19 | Dayton | 236 |
| candidate_4 | 93 | Dayton | 236 |
| candidate_5 | 42 | Dayton | 236 |
| candidate_1 | 61 | Toledo | 332 |
| candidate_2 | 78 | Toledo | 332 |
| candidate_3 | 71 | Toledo | 332 |
| candidate_4 | 70 | Toledo | 332 |
| candidate_5 | 52 | Toledo | 332 |
+-------------+-------+----------+--------------+
What would be the most effective way to accomplish this in R?