簡體   English   中英

獲取一年中的一周

[英]Get the month from the week of the year

假設我們有這個:

ex <- c('2012-41')

這代表了從2012年開始的第41周。我將如何從中獲得這個月?

由於一周可能在兩個月之間,我將有興趣獲得該周開始的月份(今年十月)。

不重復如何從R中的日期中提取月份 (沒有像%Y-%m-%d這樣的標准日期格式)。

你可以嘗試:

ex <- c('2019-10')

splitDate <- strsplit(ex, "-")

dateNew <- as.Date(paste(splitDate[[1]][1], splitDate[[1]][2], 1, sep="-"), "%Y-%U-%u")

monthSelected <- lubridate::month(dateNew)

3

我希望這有幫助!

這取決於周的定義。 有關兩周可能的定義,請參閱?strptime%V%W的討論。 我們使用下面的%V ,但如果需要,該功能允許指定另一個。 該函數對x的元素執行sapply ,對於每個這樣的元素,它將年份提取為yr並以sq為單位形成該年份的所有日期的序列。 然后,它將這些日期轉換為年 - 月,並查找該序列中x的當前組件的第一次出現,最后提取匹配的月份。

yw2m <- function(x, fmt = "%Y-%V") {
  sapply(x, function(x) {
    yr <- as.numeric(substr(x, 1, 4))
    sq <- seq(as.Date(paste0(yr, "-01-01")), as.Date(paste0(yr, "-12-31")), "day")
    as.numeric(format(sq[which.max(format(sq, fmt) == x)], "%m"))
  })
}

yw2m('2012-41')
## [1] 10

以下內容將將年周添加到年周格式化字符串的輸入中,並將日期向量作為字符返回。 lubridate包的周()函數將添加對應於相關周末的日期。 請注意,例如我在'ex'變量中添加了另一個案例到第52周,並返回Dec-31st

library(lubridate)

ex <- c('2012-41','2016-4','2018-52')

dates <- strsplit(ex,"-")
dates <- sapply(dates,function(x) {
  year_week <- unlist(x)
  year <- year_week[1]
  week <- year_week[2]
  start_date <- as.Date(paste0(year,'-01-01'))
  date <- start_date+weeks(week)
  #note here: OP asked for beginning of week.  
  #There's some ambiguity here, the above is end-of-week; 
  #uncommment here for beginning of week, just subtracted 6 days.  
  #I think this might yield inconsistent results, especially year-boundaries
  #hence suggestion to use end of week.  See below for possible solution
  #date <- start_date+weeks(week)-days(6)

  return (as.character(date))
})

產量:

> dates
[1] "2012-10-14" "2016-01-29" "2018-12-31"

只需從這些完整日期獲取月份:

month(dates)

產量:

> month(dates)
[1] 10  1 12

暫無
暫無

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

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