簡體   English   中英

在 data.table R 中匯總具有最早開始和最晚結束以及最大值的相同標識符的行

[英]Summarize rows with identical identifiers with earliest start and latest end and highest value in data.table R

以下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)]但不知道如何將它與最早的開始和結束日期結合起來。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM