I have a dataframe that shows election results by constituency and party. I need to find the party with the most votes for each constituency.
My df looks like this
# gss party votes
1 W07000049 Labour 22662
2 W07000049 Conservative 5901
3 W07000049 LibDem 941
3 W07000058 Labour 5951
3 W07000058 LibDem 1741
3 W07000058 Conservative 852
I would like to Cast it so the unique party names become my column names, like this
# gss Labour Conservative LibDem
1 W07000049 22662 5901 941
2 W07000058 5951 1741 941
On this dataframe I could then use which.max like so
x$win <- colnames(df)[apply(df, 1, function(x) which.max(x)[1])]
I've tried using dcast from reshape2 http://seananderson.ca/2013/10/19/reshape.html but am unable to apply it. How can I find the winning party of each constituency?
P.S. I'm a beginner so please let me know if I can explain this better