如何在cbind/aggregate中重命名变量?
我有以下代码行:如何在cbind/aggregate中重命名变量?,r,rename,R,Rename,我有以下代码行: 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 Northwester
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
下面是一个
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)
inc_ag%
重命名(暴力事件=V1,非暴力事件=V2)
无需引用参数名称:它们不是字符串。
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))
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)