How do I rename variables in cbind/aggregate?

Viewed 35

I have the following line of code:

inc_ag <- aggregate(cbind(inc2$SUM_violent, inc2$SUM_nonviolent) ~ District + MicrozoneID + Period, data = inc2, FUN = sum, na.rm=TRUE)

        District          MicrozoneID                    Period V1 V2
1   Northwestern    Northwestern: 61A   2019-02-06 - 2019-03-06 3   1
2   Northwestern    Northwestern: 61B   2019-02-06 - 2019-03-06 1   0
3   Northwestern    Northwestern: 61D   2019-02-06 - 2019-03-06 3   2
4   Northwestern    Northwestern: 62A   2019-02-06 - 2019-03-06 0   2

The output of this code has the sum violent and sum nonviolent variables as V1 and V2. How would I rename it so I can call them violentIncidents and nonViolentIncidents?

Similarily, when I make the code "long"

inc_aglong <- xtabs(SUM_violent ~ District + MicrozoneID + Period, data = inc_ag)
inc_aglong <- as.data.frame(inc_aglong)

        District     MicrozoneID                     Period Freq
1   Northwestern    Northern: 53A   2019-02-06 - 2019-03-06 0
2   Southern        Northern: 53A   2019-02-06 - 2019-03-06 0
3   Southwestern    Northern: 53A   2019-02-06 - 2019-03-06 0
4   Northwestern    Northern: 53B   2019-02-06 - 2019-03-06 0
5   Southern        Northern: 53B   2019-02-06 - 2019-03-06 0
6   Southwestern    Northern: 53B   2019-02-06 - 2019-03-06 0
7   Northwestern    Northwestern: 61A   2019-02-06 - 2019-03-06 3

The variable names also do not show, NOR can I add more than one sum variable.

Thank you.

dput:

structure(list(District = c("Northwestern", "Northwestern", "Northwestern", 
"Northwestern"), MicrozoneID = c("Northwestern: 61A", "Northwestern: 61B", 
"Northwestern: 61D", "Northwestern: 62A"), Period = c("2019-02-06 - 2019-03-06", 
"2019-02-06 - 2019-03-06", "2019-02-06 - 2019-03-06", "2019-02-06 - 2019-03-06"
), V1 = c(3, 1, 3, 0), V2 = c(1, 0, 2, 2)), class = "data.frame", row.names = c(NA, 
-4L))
1 Answers

Here's a dplyr solution:

inc_ag <- aggregate(cbind(inc2$SUM_violent, inc2$SUM_nonviolent) ~ District + MicrozoneID + Period, data = inc2, FUN = sum, na.rm=TRUE) %>%
rename(violentIncidents = V1, nonviolentIncidents = V2)
Related