Как переименовать переменные в cbind / aggregate? - PullRequest
2 голосов
/ 03 апреля 2020

У меня есть следующая строка кода:

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

Вывод этого кода имеет сумму ненасильственных переменных суммы как V1 и V2. Как бы я переименовал его, чтобы я мог называть их violentIncidents и nonViolentIncidents?

Точно так же, когда я делаю код "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

Имена переменных также не отображаются, NOR я могу добавьте более одной переменной суммы.

Спасибо.

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 Ответ

2 голосов
/ 03 апреля 2020

Вот решение dplyr:

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)
...