【问题标题】:Summarize rows with identical identifiers with earliest start and latest end and highest value in data.table R汇总具有相同标识符的行,其中最早开始和最晚结束以及data.table R中的最大值
【发布时间】:2021-08-20 17:09:08
【问题描述】:

关注data.table

dt <- data.table(
  ID= c(1,2,2,2,2),
  Value1 = c('a','b','a','a','a'),
  Start = c('2001-01-01','2000-01-01','2000-02-02','2000-03-03','2000-03-03'),
  End = c('2002-01-01','2001-01-01','2001-02-02','2001-03-03','2001-03-03'),
  Value_max = c(2,50,20,40,80)
)
   ID Value1      Start        End Value_max
1:  1      a 2001-01-01 2002-01-01         2
2:  2      b 2000-01-01 2001-01-01        50
3:  2      a 2000-02-02 2001-02-02        20
4:  2      a 2000-03-03 2001-03-03        40
5:  2      a 2000-03-03 2001-03-03        80

我想合并具有相同IDValue1 的行,提取最早的Start、最新的End 和最高的Value_max。 我用过dt[,SD.[which.max(Value_max)],by=.c(ID,Value1)]但不知道如何将它与最早的开始和结束日期结合起来。

【问题讨论】:

    标签: r data.table subset


    【解决方案1】:

    minmax 似乎足够了:

    dt[,.(earliest = min(Start),latest = max(End), value_max = max(Value_max)),by=.(ID,Value1)]
       ID Value1   earliest     latest value_max
    1:  1      a 2001-01-01 2002-01-01         2
    2:  2      b 2000-01-01 2001-01-01        50
    3:  2      a 2000-02-02 2001-03-03        80
    

    【讨论】:

      猜你喜欢
      • 2021-08-11
      • 1970-01-01
      • 2021-12-20
      • 2021-09-29
      • 2020-12-04
      • 1970-01-01
      • 1970-01-01
      • 2016-08-06
      • 2013-11-20
      相关资源
      最近更新 更多