I would like to calculate the margin of victory. I uploaded an example of my dataset, where there are three cities, two years, if the candidate won the election in that municipality (1 = yes, 0 = no) or not, the share of votes received by him or her, and the margin of victory.
The margin will be given by calculating the difference of the share of votes obtained by the winner candidate and the loser. I cannot figure out how to do it in R.
city year elected votes_share margin
<chr> <dbl> <dbl> <dbl> <dbl>
A 1 1 50 40
B 1 1 60 40
C 1 1 70 40
A 1 0 10 -50
B 1 0 20 -50
C 1 0 30 -50
A 2 1 60 40
B 2 1 70 40
C 2 1 80 60
A 2 0 20 20
B 2 0 30 30
C 2 0 20 20
We can use
library(dplyr)
df1 %>%
group_by(city, year) %>%
mutate(margin2 = sum(vote_share[elected == 1]) - sum(vote_share[elected == 0]))