[英]Last Day of Month Function, given Year and Month
在多次單步執行代碼后,我無法找到具體給出此錯誤的內容。 我希望之前有人見過這個錯誤。
以下是我認為與問題相關的內容:
#### Load packages
library(lubridate)
MONTH <- 1
YEAR <- 2018
# Last day of month
last_day_of_mth <- function(YEAR, MONTH){
MONTH_BEGIN <- as.POSIXlt(paste0(YEAR, "-", MONTH, "-1"))
MONTH_END <- MONTH_BEGIN
day(MONTH_END) <- day(MONTH_BEGIN)
month(MONTH_END) <- month(MONTH_END) + 1
day(MONTH_END) <- day(MONTH_END) - 1
return(as.character(MONTH_END))
}
此代碼通過source()
加載一堆外部文件,這些文件不包含任何其他包或其他功能。 他們只是從Google Analytics API查詢數據,或者他們加載.csv文件,操縱數據框,並將適當的輸出吐出為.csv文件。
出於某些奇怪的原因,在通過source()
運行這10個文件之后,它會吐出來
> last_day_of_mth(2018, 1)
[1] "2018-03-02 06:00:00"
這顯然是不正確的 - 它應該是2018-01-31
。
這是兩個解決方案。 即使year
和month
都是向量而不是這里顯示的標量,兩者都可以工作。
1)as.Date.yearmon首先將輸入轉換為"yearmon"
對象,然后使用帶有frac=1
參數的as.Date
將其轉換為"Date"
類。
library(zoo)
# input
year <- 2018
month <- 2
ym <- as.yearmon(paste(year, month, sep = "-"))
as.Date(ym, frac = 1)
## [1] [1] "2018-02-28"
2)基礎使用fom
(月初)的基礎解決方案從R中找出一個月的天數如下。 首先,我們將年份和月份轉換為該月中第一個的"Date"
類對象dat1
,並添加32,這足以進入下個月。 然后使用fom
查找該月的第一個並減去1以獲得輸入年/月的最后日期。
fom <- function(x) as.Date(cut(x, "month"))
dat1 <- as.Date(paste(year, month, 1, sep = "-"))
fom(dat1 + 32) - 1
## [1] "2018-02-28"
另一種選擇可能是使用Hmisc
庫。 人們可以找到使用year
和month
后一個月內的最大天數,以及day=1
來確定日期。 然后找出該月的最大天數。
最后使用year
, month
和max number of days in month
來確定該月的最后日期。
我創建了一個函數lastDayofMonth
library(Hmisc)
lastDayofMonth <- function(year, month){
as.Date(sprintf("%4d-%2d-%2d", year, month,
monthDays(as.Date(sprintf("%4d-%2d-%2d", year, month, 1)))
))
}
> lastDayofMonth(2018,2)
#[1] "2018-02-28"
> lastDayofMonth(2018,3)
#[1] "2018-03-31"
> lastDayofMonth(2017,3)
#[1] "2017-03-31"
> lastDayofMonth(2000,2)
#[1] "2000-02-29"
調整自己的代碼,並繼續使用lubridate
:
last_day_of_mth <- function(YEAR, MONTH){
ymd(paste0(YEAR, "-", MONTH, "-1")) %>%
ceiling_date(., "month") %>%
{.-days(1)}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.