簡體   English   中英

給定月份中每一天的一年中的某一天

[英]Day of the year for each day in a given month

我想在 R 中有一個 function month2doty() ,如果提供了一個代表一個月的數字(例如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

我的世界不存在閏年。 我在下面提供了一個可能的答案,但我確定有更好的解決方案嗎?

這是在基礎 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和來自days_in_monthlubridate的另一種變體

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

我目前對此的解決方案是每次調用 function 時查找表的構造有點尷尬:

month2doty <- function(mon=1){
  require(lubridate)
  alldays <- seq(from=ymd("2015-01-01"), length.out=365, by="days")
  lookuptable <- data.frame(month=month(alldays), day=day(alldays), doty=yday(alldays) )
  monthdata <- subset(lookuptable, lookuptable$month==mon)
  return(monthdata$doty)
}

month2doty(2)

它就像那樣工作得很好,但我想知道我在這里是否缺少更清潔的解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM