这是在基础 R 中执行此操作的另一种方法。我们在月初和下个月之间创建一个长度为 2 的序列,然后生成它们之间的所有日期。我们在format 中使用%j 来显示这些日期的一年中的哪一天。
month2doty <- function(x) {
days <- seq(as.Date(paste0(format(Sys.Date(), "%Y"), "-", x, "-01")),
by = "1 month", length.out = 2)
as.integer(format(seq(days[1], days[2] - 1, by = "day"), "%j"))
}
month2doty(2)
# [1] 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
# 54 55 56 57 58 59
month2doty(12)
# [1] 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
# 354 355 356 357 358 359 360 361 362 363 364 365
或仅使用一次seq 和来自lubridate 的days_in_month 的另一个变体
library(lubridate)
month2doty <- function(x) {
days <- as.Date(paste0(format(Sys.Date(), "%Y"), "-", x, "-01"))
as.integer(format(seq(days, days + days_in_month(x) - 1, by = "day"), "%j"))
}
如果我们不想区别对待闰年,我们可以硬编码年份(就像在 OP 中一样)
month2doty <- function(x) {
days <- seq(as.Date(paste0("2015-", x, "-01")), by = "1 month", length.out = 2)
as.integer(format(seq(days[1], days[2] - 1, by = "day"), "%j"))
}
和
month2doty <- function(x) {
days <- as.Date(paste0("2015-", x, "-01"))
as.integer(format(seq(days, days + days_in_month(x) - 1, by = "day"), "%j"))
}