【问题标题】:How do I rename variables in cbind/aggregate?如何重命名 cbind/aggregate 中的变量?
【发布时间】:2020-07-15 21:13:24
【问题描述】:

我有以下代码行:

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。我将如何重命名它以便我可以称它们为暴力事件和非暴力事件?

同样,当我将代码设置为“长”时

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

变量名也不显示,我也不能添加多个 sum 变量。

谢谢。

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

【问题讨论】:

    标签: r rename


    【解决方案1】:

    这是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)
    

    【讨论】:

    • 无需引用参数名称:它们不是字符串
    猜你喜欢
    • 1970-01-01
    • 2012-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-13
    • 2019-11-24
    • 2021-07-18
    相关资源
    最近更新 更多