0

I have the following table

District    pnum    violentIncidents    nonviolentIncidents
Central 1   84  298
Eastern 1   82  178
Northeastern    1   91  313
Northern    1   47  247
Central 2   75 234
Eastern 2   33 224
Northeastern    2   254 33
Northern    2   344 244

However, I want it to be reshaped so that Pnum is horizontal, and for each district I have their totals for that pnum.

enter image description here

Where for each pnum, I have a listing of the variables and their counts by district.

Is this possible? Thank you.

EDIT: How would I re do it so it looks like this?

enter image description here

user13203033
  • 123
  • 7

1 Answers1

0

Try this:

#Data
df <- structure(list(District = structure(c(1L, 2L, 3L, 4L, 1L, 2L, 
3L, 4L), .Label = c("Central", "Eastern", "Northeastern", "Northern"
), class = "factor"), pnum = c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L
), violentIncidents = c(84L, 82L, 91L, 47L, 75L, 33L, 254L, 344L
), nonviolentIncidents = c(298L, 178L, 313L, 247L, 234L, 224L, 
33L, 244L)), class = "data.frame", row.names = c(NA, -8L))

#Code
library(tidyr)

pivot_wider(df,id_cols = District,names_from = pnum,values_from = c(violentIncidents,nonviolentIncidents))

# A tibble: 4 x 5
  District     violentIncidents_1 violentIncidents_2 nonviolentIncidents_1 nonviolentIncidents_2
  <fct>                     <int>              <int>                 <int>                 <int>
1 Central                      84                 75                   298                   234
2 Eastern                      82                 33                   178                   224
3 Northeastern                 91                254                   313                    33
4 Northern                     47                344                   247                   244
Duck
  • 39,058
  • 13
  • 42
  • 84
  • This works, but what if I want to have the values (violent incidents etc) under each district? So I would have only the period numbers across the top. See the OP post for example I updated – user13203033 Jul 14 '20 at 17:07