[英]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.