r - 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) 。如何使用此输入获得预期输出。
解决方案
我想你可能想检查 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
了解最后两种情况。
推荐阅读
- python - 下载 SQL for Python 时出错
- php - 当标签被格式化并从 url 检索时,SQL 按标签搜索文章
- telerik-reporting - SUM(MAX(Fields.Amount)) 在 Telerik 报告中不起作用
- mysql - 删除和插入行mysql
- php - 根据选择选项值变化动态加载html表格
- sql - 如何在存储过程中从查询中设置输出参数值
- java - 带有父子指针的 JAXB
- css - 有没有办法根据它所在的容器来设置 Web 组件的样式?
- sql - 如何将 cmd 查询输出到 SQL Server 数据库?
- ios - Xamarin 表单:创建分发证书和 .p12 文件时出现问题