【问题标题】:r - Getting start and end date of any year,quarters or months given as inputr - 获取作为输入的任何年份、季度或月份的开始和结束日期
【发布时间】:2020-07-20 02:33:55
【问题描述】:

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

例子:

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,它给出了准确的输出,但输入它预计是日期。

代码: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) 。如何使用此输入获得预期输出。

【问题讨论】:

  • 请尝试提供您正在处理的特定示例代码,以便我们更好地理解问题并重现它。提供源代码和结果以及预期的结果。
  • 请提供一个代表。很难理解你的问题。
  • 请更具体地说明您的要求。 lubridate 包是您处理所有日期/时间的朋友 - zoo 中的 as.yearqtr 函数也可能有助于输入季度。
  • 如果用户提供季度和年份作为输入,如何获取其对应的日期范围例如。输入 ("Q1","2020) ,输出应为 2020-01-01 - 2020-03-31

标签: r date lubridate


【解决方案1】:

我想你可能想查看 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 package (v0.3.0) 于 2020-07-20 创建

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

【讨论】:

  • 如果我回答了你所有的问题,你应该接受这个答案!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多