从一年中的星期中获取月份

时间:2019-03-05 16:12:29

标签: r xts posixct

让我们说这个:

ex <- c('2012-41')

这代表从2012年开始的第41周。我如何从中获得月份?

由于一周可能在两个月之间,所以我很想获得该周开始的月份(这里是10月)。

不可与How to extract Month from date in R重复(没有标准日期格式,例如%Y-%m-%d)。

3 个答案:

答案 0 :(得分:3)

您可以尝试:

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

我希望这会有所帮助!

答案 1 :(得分:1)

这取决于周的定义。有关周的两种可能的定义,请参见%V中对%W?strptime的讨论。我们在下面使用%V,但是如果需要,该函数允许一个指定另一个。该函数在sapply的元素上执行x,对于每个这样的元素,它将年份提取到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

答案 2 :(得分:0)

The following will add the week-of-year to an input of year-week formatted strings and return a vector of dates as character. The lubridate package weeks() function will add the dates corresponding to the end of the relevant week. Note for example I've added an additional case in your 'ex' variable to the 52nd week, and it returns 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))
})

Yields:

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

And to simply get the month from these full dates:

month(dates)

Yields:

> month(dates)
[1] 10  1 12