【问题标题】:data.table aggregation by one column using the maximum value of another column - R使用另一列的最大值按一列聚合data.table - R
【发布时间】:2019-05-06 13:49:57
【问题描述】:

我有一个 data.table DT,我想使用另一列(月)的最大值按一列(年)聚合。这是我的 data.table 的示例。

> DT <- data.table(month = c("2016-01", "2016-02", "2016-03", "2017-01", "2017-02", "2017-03")
                  , col1 = c(3,5,2,8,4,9)
                  , year = c(2016, 2016,2016, 2017,2017,2017))

> DT
     month col1 year
1: 2016-01    3 2016
2: 2016-02    5 2016
3: 2016-03    2 2016
4: 2017-01    8 2017
5: 2017-02    4 2017
6: 2017-03    9 2017

想要的输出

> ## desired output
    > DT
         month col1 year desired_output
    1: 2016-01    3 2016     2
    2: 2016-02    5 2016     2
    3: 2016-03    2 2016     2
    4: 2017-01    8 2017     9
    5: 2017-02    4 2017     9
    6: 2017-03    9 2017     9

按年份聚合,所需的输出应该是最近一个月的 col1 的值。但不知何故,下面的代码不起作用,它给了我一个警告并返回 NA。我做错了什么?

> ## wrong output
 > DT[, output := col1[which.max(month)], by = .(year)]
    Warning messages:
    1: In which.max(month) : NAs introduced by coercion
    2: In which.max(month) : NAs introduced by coercion
> DT
     month col1 year output
1: 2016-01    3 2016     NA
2: 2016-02    5 2016     NA
3: 2016-03    2 2016     NA
4: 2017-01    8 2017     NA
5: 2017-02    4 2017     NA
6: 2017-03    9 2017     NA

【问题讨论】:

    标签: r data.table max aggregate


    【解决方案1】:

    我们通过从zoo 转换为yearmon 类来获取'month 中最大值的索引,并在创建按'year' 分组的'desired_output' 列时使用它从'col1' 中获取相应的值

    library(zoo)
    library(data.table)
    DT[, desired_output := col1[which.max(as.yearmon(month))], .(year)]
    DT
    #     month col1 year desired_output
    #1: 2016-01    3 2016              2
    #2: 2016-02    5 2016              2
    #3: 2016-03    2 2016              2
    #4: 2017-01    8 2017              9
    #5: 2017-02    4 2017              9
    #6: 2017-03    9 2017              9
    

    或者提取“月”,得到max值的索引

    DT[, desired_output := col1[which.max(month(as.IDate(paste0(month,
                      "-01"))))], .(year)]
    

    【讨论】:

    • 那么,which.max 不适用于字符串列? max(DT$month) 有效,但不是 which.max(DT$month)
    • 似乎 which.max 仅适用于数值。非常感谢您的帮助,现在很有意义。将 which.max 功能也扩展到字符变量会很好
    • 对于Date 对象,最好在Date 类上申请,以避免任何问题。
    猜你喜欢
    • 1970-01-01
    • 2022-11-08
    • 1970-01-01
    • 2018-01-29
    • 1970-01-01
    • 1970-01-01
    • 2020-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多