简体   繁体   English

在 R 中获取每个月的第一天和最后一天

[英]Getting first and last day of each month in R

I need to get the row of the first and last day of each month in a big data frame where I need to apply operations that cover accurately each month, using a for loop.我需要在一个大数据框中获取每个月的第一天和最后一天的行,我需要使用 for 循环应用每个月准确覆盖的操作。 Unfortunately, the data frame is not very homogeneous.不幸的是,数据框不是很均匀。 Here a reproducible example to work upon:这是一个可重复的示例:

dataframe <- data.frame(Date=c(seq.Date(as.Date("2020-01-01"),as.Date("2020-01-31"),by="day"),
    seq.Date(as.Date("2020-02-01"),as.Date("2020-02-28"),by="day"),seq.Date(as.Date("2020-03-02"),
    as.Date("2020-03-31"),by="day")))

We can create a grouping column by converting to yearmon and then get the first and last我们可以通过转换为yearmon来创建一个分组列,然后得到第一个和最后一个

library(zoo)
library(dplyr)
dataframe %>% 
   group_by(yearMon = as.yearmon(Date)) %>%
   summarise(FirstDay = first(Date), LastDay = last(Date))
# A tibble: 3 x 3
#  yearMon   First      Last      
#* <yearmon> <date>     <date>    
#1 Jan 2020  2020-01-01 2020-01-31
#2 Feb 2020  2020-02-01 2020-02-28
#3 Mar 2020  2020-03-02 2020-03-31

If it the first and last day irrespective of the data如果是第一天和最后一天,无论数据如何

library(lubridate)
dataframe %>% 
   group_by(yearMon = as.yearmon(Date)) %>%
   summarise(First = floor_date(first(Date), 'month'), 
             Last = ceiling_date(last(Date), 'month')-1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM