dplyr - 获取每年的最新价值

Ale*_*alm 16 r dplyr

我有一个看起来像这样的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
..        ...    ...  ...
Run Code Online (Sandbox Code Playgroud)

几年的日期范围.

我想得到value每年的最新价值(不一定是31-12).有没有办法使用如下的成语:d %>% group_by(year) %>% summarise(...)

akr*_*run 31

这里有一些选择

library(dplyr)
d %>% 
  group_by(year) %>%
  summarise(value=last(value))
Run Code Online (Sandbox Code Playgroud)

或者可能(在描述中不是很清楚)

d %>% 
  group_by(year) %>%
  slice(which.max(date)) %>%
  select(value) 
Run Code Online (Sandbox Code Playgroud)

要么

d %>%
  group_by(year) %>%
  filter(date==max(date)) %>%
  select(value)
Run Code Online (Sandbox Code Playgroud)

或者我们可以arrange用来订购'日期'(如果没有订购)并获得last价值

d %>%
  group_by(year) %>%
  arrange(date) %>%
  summarise(value=last(value))
Run Code Online (Sandbox Code Playgroud)

如果你想尝试data.table,这里是一个

library(data.table)
setDT(d)[, value[which.max(date)], year]
Run Code Online (Sandbox Code Playgroud)

或者@David Arenburg评论道

 unique(setDT(d)[order(-date)], by = "year")
Run Code Online (Sandbox Code Playgroud)