0

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!

LuizZ
  • 808
  • 1
  • 9
  • 20
chr
  • 3
  • 1

1 Answers1

0

If what you want is:

To get the total votes to each party in every single state

Then what you want is to sum party votes grouped by states. You can do it with dplyr:

library(dplyr)

party_state_totals <- DS %>% 
  group_by(st) %>% 
  summarise(p1_tot = sum(p1),
            p2_tot = sum(p2),
            p3_tot = sum(p3))
LuizZ
  • 808
  • 1
  • 9
  • 20