从yearmon对象计算月份的第一天和最后一天

问题描述 投票:0回答:3

我有一个简单的df,在yearmon类中有一列日期:

df <- structure(list(year_mon = structure(c(2015.58333333333, 2015.66666666667, 
                                  2015.75, 2015.83333333333, 2015.91666666667, 2016, 2016.08333333333, 
                                  2016.16666666667, 2016.25, 2016.33333333333), class = "yearmon")), class = c("tbl_df", 
                                                                                                               "tbl", "data.frame"), row.names = c(NA, -10L))

我想要一个简单的方法,最好使用基数R,lubridatexts / zoo来计算每个月的第一天和最后一天。

我已经看过其他包这样做了,但是如果可能的话,我想坚持上述。

r xts zoo lubridate
3个回答
2
投票

我们可以用

library(dplyr)
library(lubridate)
library(zoo)
df %>% 
   mutate(firstday = day(year_mon), last = day(as.Date(year_mon, frac = 1)))

2
投票

使用基数R,您可以使用yearmonas.Date对象转换为日期,这将为您提供该月的第一天。在最后一天,我们可以将日期增加一个月(1/12)并从中减去1天。

df$first_day <- as.Date(df$year_mon)
df$last_day <- as.Date(df$year_mon + 1/12) - 1
df  

#   year_mon      first_day  last_day  
#   <S3: yearmon> <date>     <date>    
# 1 Aug 2015      2015-08-01 2015-08-31
# 2 Sep 2015      2015-09-01 2015-09-30
# 3 Oct 2015      2015-10-01 2015-10-31
# 4 Nov 2015      2015-11-01 2015-11-30
# 5 Dec 2015      2015-12-01 2015-12-31
# 6 Jan 2016      2016-01-01 2016-01-31
# 7 Feb 2016      2016-02-01 2016-02-29
# 8 Mar 2016      2016-03-01 2016-03-31
# 9 Apr 2016      2016-04-01 2016-04-30
#10 May 2016      2016-05-01 2016-05-31

1
投票

如图所示,使用动物园的as.Date.yearmonfrac指定使用月份的小数金额,以便0表示月份开始,1表示结束。 frac的默认值为0。

如果您使用的是yearmon,那么您必须已经在使用zoo(因为这是定义yearmon方法的地方)所以这不涉及使用超出您已经使用的任何其他包。

如果您使用的是dplyr,可以选择用transform替换mutate

transform(df, first = as.Date(year_mon), last = as.Date(year_mon, frac = 1))

得到:

   year_mon      first       last
1  Aug 2015 2015-08-01 2015-08-31
2  Sep 2015 2015-09-01 2015-09-30
3  Oct 2015 2015-10-01 2015-10-31
4  Nov 2015 2015-11-01 2015-11-30
5  Dec 2015 2015-12-01 2015-12-31
6  Jan 2016 2016-01-01 2016-01-31
7  Feb 2016 2016-02-01 2016-02-29
8  Mar 2016 2016-03-01 2016-03-31
9  Apr 2016 2016-04-01 2016-04-30
10 May 2016 2016-05-01 2016-05-31
© www.soinside.com 2019 - 2024. All rights reserved.