I have an electoral dataset DS where columns are states st, districts di, different parties p1, p2, p3 and total votes tot like this (but much longer):
DS <- read.table(header=TRUE, 
  text="
st di p1 p2 p3 tot
01 01 10 20 12 42
01 02 12 91 12 115
02 01 20 23 40 83
02 02 10 13 12 35
02 03 30 20 40 90")
I want to calculate the addition of all values from p1 where st == 01 and then all values from p1 when st==02, and so on, in order to get the total votes to each party in every single state. I thought there must be a way to do sum(DS$p1) under some logical condition (like st==01), but I don’t know how to do it. Any ideas? Thanks a lot!
 
    