首页 > 解决方案 > 给定月份中每一天的一年中的某一天

问题描述

我想month2doty()在 R 中有一个函数,如果提供了一个代表一个月的数字(例如2二月),则返回一个向量,其中包含该月每一天的一年32, 33, 34, …, 59中的某一天(二月也是如此):

> 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

我的世界不存在闰年。我在下面提供了一个可能的答案,但我确定有更好的解决方案吗?

标签: rlubridate

解决方案


这是在基础 R 中执行此操作的另一种方法。我们在月初和下个月之间创建一个长度为 2 的序列,然后生成它们之间的所有日期。我们使用%jinformat来显示这些日期的一年中的哪一天。

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或仅使用一次days_in_month的另一种变体lubridate

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"))
}

推荐阅读