# 编写函数
last_quarter_day = function(dates) {
dates = as.Date(dates)
month = as.integer(format(dates, '%m'))
year = as.integer(format(dates, '%Y'))
quarter = ceiling(month / 3)
day = c('12-31', '03-31', '06-30', '09-30')[quarter]
year[quarter == 1] = year[quarter == 1] - 1
as.Date(sprintf('%d-%s', year, day))
}This is a post with executable code.
# 测试函数
x = c("2021-10-14", "2019-01-11")
last_quarter_day(x)[1] "2021-09-30" "2018-12-31"
# 系统信息
sessionInfo()R version 4.2.3 (2023-03-15 ucrt)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19045)
Matrix products: default
locale:
[1] LC_COLLATE=Chinese (Simplified)_China.utf8
[2] LC_CTYPE=Chinese (Simplified)_China.utf8
[3] LC_MONETARY=Chinese (Simplified)_China.utf8
[4] LC_NUMERIC=C
[5] LC_TIME=Chinese (Simplified)_China.utf8
attached base packages:
[1] stats graphics grDevices utils datasets methods base
loaded via a namespace (and not attached):
[1] htmlwidgets_1.6.4 compiler_4.2.3 fastmap_1.2.0 cli_3.6.2
[5] tools_4.2.3 htmltools_0.5.8.1 rstudioapi_0.16.0 yaml_2.3.8
[9] rmarkdown_2.27 knitr_1.47 jsonlite_1.8.8 xfun_0.45
[13] digest_0.6.35 rlang_1.1.4 evaluate_0.24.0