dplyr - 获取每年的最后一个值

dplyr - Get last value for each year

我有一个 tbl_df 看起来像这样:

> d
Source: local data frame [3,703 x 3]

         date  value year
1  2001-01-01 0.1218 2001
2  2001-01-02 0.1216 2001
3  2001-01-03 0.1216 2001
4  2001-01-04 0.1214 2001
5  2001-01-05 0.1214 2001
..        ...    ...  ...

其中日期跨越数年。

我想获取每年 value 的最新值(并非始终是 31-12)。有没有办法使用诸如 d %>% group_by(year) %>% summarise(...) 之类的成语来做到这一点?

这里有一些选项

library(dplyr)
d %>% 
  group_by(year) %>%
  summarise(value=last(value))

也可能是(描述的不是很清楚)

d %>% 
  group_by(year) %>%
  slice(which.max(date)) %>%
  select(value) 

d %>%
  group_by(year) %>%
  filter(date==max(date)) %>%
  select(value)

或者我们可以使用 arrange 对 'date' 进行排序(以防未排序)并获得 last

d %>%
  group_by(year) %>%
  arrange(date) %>%
  summarise(value=last(value))

如果您想尝试 data.table,这里有一个

library(data.table)
setDT(d)[, value[which.max(date)], year]

或@David Arenburg 评论

 unique(setDT(d)[order(-date)], by = "year")