首页 > 解决方案 > r - 获取作为输入的任何年份、季度或月份的开始和结束日期

问题描述

对于给定的时期,无论是季度、月还是年,如何获取开始和结束日期。

例子:

Input : c("Q1","2020)  
Expected Output:  2020-01-01 - 2020-03-31 

Input : c(11,12,2019)
Expected Output:   2019-11-01 - 2019-11-31 

                                                            

我已经尝试过 Package timeperiodsR ,它给出了准确的输出,但输入它预计是 date 。

代码:this_month(x = "2019-01-01")

输出:时间段:2019-01-01(星期二)- 2019-01-31(星期四)

timeperiodsR 期望输入应该是一个日期,例如。x =“2019-01-01”。但是我们的输入将类似于 x= c("01","2019) (month ,year) 或 (quarter,year) 。如何使用此输入获得预期输出。

标签: rdatelubridate

解决方案


我想你可能想检查 R 包zoo

library(zoo)
#> 
#> Attaching package: 'zoo'
#> The following objects are masked from 'package:base':
#> 
#>     as.Date, as.Date.numeric

# year
input <- c("2010", "2015", "2019", "2020")
as.Date(paste0(input, "-01-01")) # start date
#> [1] "2010-01-01" "2015-01-01" "2019-01-01" "2020-01-01"
as.Date(paste0(input, "-12-31")) # end data
#> [1] "2010-12-31" "2015-12-31" "2019-12-31" "2020-12-31"

# month
input <- c("2010-01", "2015-05", "2019-09", "2020-12")
input_month <- as.yearmon(input)
as.Date(input_month) # start date
#> [1] "2010-01-01" "2015-05-01" "2019-09-01" "2020-12-01"
as.Date(input_month, frac = 1) # end date
#> [1] "2010-01-31" "2015-05-31" "2019-09-30" "2020-12-31"

# quarter
input <- c("2010 Q4", "2015 Q2", "2019 Q3", "2020 Q1")
input_qrt <- as.yearqtr(input) # transform into yearqrt objects
as.Date(input_qrt) # start date
#> [1] "2010-10-01" "2015-04-01" "2019-07-01" "2020-01-01"
as.Date(input_qrt, frac = 1)
#> [1] "2010-12-31" "2015-06-30" "2019-09-30" "2020-03-31"

reprex 包(v0.3.0)于 2020-07-20 创建

查看 和 的帮助页面?zoo::as.yearmon?zoo::as.yearqrt了解最后两种情况。


推荐阅读