dplyr-获取每年的最后一个值 [英] dplyr - Get last value for each year
本文介绍了dplyr-获取每年的最后一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个看起来像这样的tbl_df:
I have a tbl_df that looks like this:
> 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(...)
?
I would like to get the latest value of value
for each year (which is not consistently the 31-12). Is there a way to do that using an idiom such as: d %>% group_by(year) %>% summarise(...)
?
推荐答案
以下是一些选择
library(dplyr)
d %>%
group_by(year) %>%
summarise(value=last(value))
或者可能是(描述中不太清楚)
Or may be (not very clear in the description)
d %>%
group_by(year) %>%
slice(which.max(date)) %>%
select(value)
或
d %>%
group_by(year) %>%
filter(date==max(date)) %>%
select(value)
或者我们可以使用 arrange
来排序日期(以防未排序)并获得 last
值
Or we can use arrange
to order the 'date' (in case it is not ordered) and get the last
value
d %>%
group_by(year) %>%
arrange(date) %>%
summarise(value=last(value))
如果您想尝试使用 data.table
,这里是一个
In case, you want to try with data.table
, here is one
library(data.table)
setDT(d)[, value[which.max(date)], year]
或@David Arenburg评论
Or as @David Arenburg commented
unique(setDT(d)[order(-date)], by = "year")
这篇关于dplyr-获取每年的最后一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文