I'm fairly new to R and am trying to do a little data analysis of congressional elections in the US (for fun as well as a project to practice R skills)
SO I have a CSV of all federal congressional elections since 1976. What I am trying to do is get an average of Dem/Rep margin across the US grouped by election year. So for example I'll have: in 1976 Dems won the house by X%, in 1978 lost by Y%, etc.
This is fairly trivial to do in excel through pivot tables but I want to learn how to do it in R. I'm sure it's also even more trivial in R if you know what you're doing lol.
Please see the image here of the calculation I want to do:
You can see from the screenshot here the white columns on the left are from my original data set and on the right two columns highlighted in blue the calculation I want to do.
The way (I think) the code should work is : group by election year, district #, what is the Dem % of vote, what is the Rep % of vote and then mutate a new column with the result of the "Dem margin" for each district.
I can then pivot this data into a new table which will show the Dem margin for each district, and from there be able to calculate average for the entire country and further calculations.
I think maybe I need to do this with a Ifelse statements nested inside of a mutate, but as a newb I'm having trouble how to format the code there.
Hopefully that makes some sense. Any ideas or someone willing to set me down on the right track?
Aucun commentaire:
Enregistrer un commentaire