获取一年中的一周

问题描述 投票:3回答:3

假设我们有这个:

ex <- c('2012-41')

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

由于一个星期可能在两个月之间,我将有兴趣获得该周开始的那个月(今年十月)。

不与How to extract Month from date in R重复(没有像%Y-%m-%d这样的标准日期格式)。

r xts posixct
3个回答
0
投票

以下内容将将年周添加到年周格式化字符串的输入中,并将日期向量作为字符返回。 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

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
投票

这取决于周的定义。有关两周可能的定义,请参阅%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
© www.soinside.com 2019 - 2024. All rights reserved.