How to get week number and year from date in R

微笑、不失礼 提交于 2021-02-04 19:47:05

问题


I am trying to get both week number and year from a date object in R.

Until then, I did it separately : I used isoweek() function to extract week and year() function to extract year. So that my data.frame has 3 variables : date, week, year

This is working except for beginning/end of year : for example, 2015 has 53 weeks and January 1st, 2016 belongs to the 53rd week of 2015 ... but with my code, it is such that 1/1/2016 is week 53 but year 2016 whereas I would like it to be week 53 in year 2015.

So is there a way in R to extract week numbers and years that make sense together ?

I know there are lots of questions about this but not found anything on this specific beginning/end of year issue.

Thanks !


回答1:


Try this. (Two steps.)

x <- as.Date("1/1/2016", "%d/%m/%Y")
format(x, "%G")
[1] "2015"

format(x, "%V")
[1] "53"

See ?strptime for details.



来源:https://stackoverflow.com/questions/46112741/how-to-get-week-number-and-year-from-date-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!