从一年中的一周中获取月份 [英] Get the month from the week of the year

查看:30
本文介绍了从一年中的一周中获取月份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有这个:

ex <- c('2012-41')

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

This represent the week 41 from the year 2012. How would I get the month from this?

因为一周可能介于两个月之间,所以我很想知道那一周开始的月份(这里是 10 月).

Since a week can be between two months, I will be interested to get the month when that week started (here October).

不重复如何从R中的日期中提取月份(没有像 %Y-%m-%d 这样的标准日期格式).

Not duplicate to How to extract Month from date in R (do not have a standard date format like %Y-%m-%d).

推荐答案

以下内容将把一年中的周添加到年-周格式字符串的输入中,并以字符形式返回日期向量.lubridate 包周()函数将添加与相关周结束相对应的日期.例如,请注意我在第 52 周的ex"变量中添加了一个额外的案例,它返回 Dec-31st

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

产量:

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

并简单地从这些完整日期中获取月份:

And to simply get the month from these full dates:

month(dates)

产量:

> month(dates)
[1] 10  1 12

这篇关于从一年中的一周中获取月份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆