按组选择最近日期的行 [英] Select row with most recent date by group

查看:40
本文介绍了按组选择最近日期的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在R中有一个数据框,其中的行代表事件,一列是事件的日期。事件发生的事件由ID列描述。因此,对于每个ID,都有多个条目。

I have a data frame in R where the rows represent events, and one column is the date of the event. The thing the event is happening to is described by an ID column. So for each ID there are multiple entries.

如何过滤数据框,以便仅保留每个ID的最新事件? ID为整数,日期格式为 mm / dd / yyyy

How do I filter the data frame so that I retain only the most recent event for each ID? The IDs are integers and the dates are in the form mm/dd/yyyy.

推荐答案

您可以尝试

library(dplyr)
df %>% 
  group_by(ID) %>%
  slice(which.max(as.Date(date, '%m/%d/%Y')))



数据



data

df <- data.frame(ID= rep(1:3, each=3), date=c('02/20/1989',
'03/14/2001', '02/25/1990',  '04/20/2002', '02/04/2005', '02/01/2008',
'08/22/2011','08/20/2009', '08/25/2010' ), stringsAsFactors=FALSE)

这篇关于按组选择最近日期的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆