简体   繁体   English

如何从R中的日期获取周数和年份

[英]How to get week number and year from date in R

I am trying to get both week number and year from a date object in R.我试图从 R 中的日期对象中获取周数和年份。

Until then, I did it separately : I used isoweek() function to extract week and year() function to extract year.在那之前,我是分开做的:我使用 isoweek() 函数来提取周和 year() 函数来提取年份。 So that my data.frame has 3 variables : date, week, year这样我的 data.frame 有 3 个变量:日期、周、年

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.除了年初/年末外,这是有效的:例如,2015 年有 53 周,2016 年 1 月 1 日属于 2015 年的第 53 周……但根据我的代码,2016 年 1 月 1 日是第 53 周但是 2016 年,而我希望它是 2015 年的第 53 周。

So is there a way in R to extract week numbers and years that make sense together ?那么在 R 中有没有办法提取一起有意义的周数和年份?

I know there are lots of questions about this but not found anything on this specific beginning/end of year issue.我知道有很多关于此的问题,但在这个特定的年初/年终问题上没有发现任何问题。

Thanks !谢谢 !

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.有关详细信息,请参阅?strptime

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM