So I'm doing some work with election data. The data I have is formatted like this:

Code:
* Example generated by -dataex-. To install: ssc install dataex
clear
input str8 state str11 county int year str9 office str23 candidate str29 party long votes byte special
"Delaware" "New Castle" 2016 "President" "Clinton, Hillary" "Democrat" 162919 0
"Delaware" "New Castle" 2016 "President" "Trump, Donald" "Republican" 85525 0
"Delaware" "New Castle" 2016 "President" "Johnson, Gary" "Libertarian" 9107 0
"Delaware" "New Castle" 2016 "President" "Stein, Jill" "Green" 3956 0
"Delaware" "New Castle" 2016 "President" "McMullin, Evan" "Independent" 514 0
"Delaware" "New Castle" 2016 "President" "other" "other" 370 0
"Delaware" "Kent" 2016 "President" "Clinton, Hillary" "Democrat" 33351 0
"Delaware" "Kent" 2016 "President" "Trump, Donald" "Republican" 36991 0
"Delaware" "Kent" 2016 "President" "Johnson, Gary" "Libertarian" 2876 0
"Delaware" "Kent" 2016 "President" "Stein, Jill" "Green" 104 0
"Delaware" "Kent" 2016 "President" "McMullin, Evan" "Independent" 109 0
"Delaware" "Kent" 2016 "President" "other" "other" 229 0
"Delaware" "Sussex" 2016 "President" "Clinton, Hillary" "Democrat" 39333 0
"Delaware" "Sussex" 2016 "President" "Trump, Donald" "Republican" 62611 0
"Delaware" "Sussex" 2016 "President" "Johnson, Gary" "Libertarian" 2774 0
"Delaware" "Sussex" 2016 "President" "Stein, Jill" "Green" 1105 0
"Delaware" "Sussex" 2016 "President" "McMullin, Evan" "Independent" 83 0
"Delaware" "Sussex" 2016 "President" "other" "other" 102 0
"Delaware" "(statewide)" 2016 "President" "Clinton, Hillary" "Democrat" 235603 0
"Delaware" "(statewide)" 2016 "President" "Trump, Donald" "Republican" 185127 0
"Delaware" "(statewide)" 2016 "President" "Johnson, Gary" "Libertarian" 14757 0
"Delaware" "(statewide)" 2016 "President" "Stein, Jill" "Green" 6103 0
"Delaware" "(statewide)" 2016 "President" "other" "other" 2224 0
With this data, I'd like to create variables based on specific races by county. For example, I'd like to be able to calculate the total votes by election in each county, the percentages each candidate got, what margin the Democratic candidate won or lost by, etc. I'm assuming the best way to do that is with a "foreach" loop, but I'm unsure what the exact code would be. The grouping would be based on the data points where state, county, year, office, and "special" are all shared, but I'm unsure how to type that out. Any ideas?