如何在R中选择每月的最后一天 [英] How to select the last day of the month in R

查看:538
本文介绍了如何在R中选择每月的最后一天的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何选择与当月最后一天相对应的数据? 例如,我有一个数据集,其中包含2000年至2016年的V1每日数据.我需要选择的是每个月的最后一天,即所有年份的31/01/200128/02/2001等.日期格式为DD/MM/YYYY.

How to select the data that correspond to the last day of the month? For example I have the dataset which contains the daily data of V1 from 2000 to 2016. All I need is to select the last day of each month, i.e the 31/01/2001, 28/02/2001 etc for all years. The date format is DD/MM/YYYY.

 V1         V2
4.59 29/12/2000
4.59 01/01/2001
4.58 02/01/2001
4.52 03/01/2001
4.54 04/01/2001
4.58 05/01/2001
......
4.09 26/01/2001
4.50 27/01/2001
4.18 28/01/2001
4.11 29/01/2001
3.54 30/01/2001
4.98 31/01/2001  <- Select this row!

推荐答案

library(data.table)
library(lubridate)

# for each unique combo of year-mon get the last entry
setDT(df)[order(V2), .(V1[which.max(V2)], V2[which.max(V2)]), by = .(year(V2), month(V2))] 
#   year month   V1         V2
#1: 2000    12 4.59 2000-12-29
#2: 2001     1 4.98 2001-01-31

这篇关于如何在R中选择每月的最后一天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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