![](/img/trans.png)
[英]Is there an easy way to create a vector following the pattern: 1st day of the month, last day of the month, 1st day of the month etc.?
[英]Enter a month and get the 1st and last day for it in the particular year
R中是否有辦法獲取指定月份的第一天和最后一天。 例如。
Input: September 2018 or any other format to specify month and year
Expected output:
1st day function (Input) -> 01-Sep-2018 or any other valid date format
Last day function (Input) -> 30-Sep-2018 or any other valid date format
使用lubridate
庫:
require(lubridate)
d <- as.Date('2018-09-01')
last_day <- d
day(last_day) <- days_in_month(last_day)
對於基本的R解決方案,我們可以定義一個輔助方法以增加月份。 然后,可以通過在月份的第一天加上一個月並減去一天來計算給定月份的最后一天:
add.months <- function(date, n) seq(date, by=paste (n, "months"), length=2 [2]
d <- as.Date('2018-09-01') # first of the month
last_day <- add.months(d, 1) - 1 # last of the month
這個SO問題賦予了add.months
輔助函數的add.months
。
我們可以在基數R中創建一個函數
get_first_and_last_date <- function(month_year) {
start_date = as.Date(paste0("01 ", month_year), "%d %b %Y")
end_date = (seq(start_date, length.out = 2, by = "month") - 1)[2]
c(start_date, end_date)
}
get_first_and_last_date('Dec 2018')
#[1] "2018-12-01" "2018-12-31"
get_first_and_last_date('Sep 2016')
#[1] "2016-09-01" "2016-09-30"
無論輸入哪種格式,請確保其前后一致。 在這里,我考慮到輸入始終是月份名稱和完整年份。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.