如何在R中从日期获取星期数和年份 [英] How to get week number and year from date in R

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

问题描述

我正在尝试从R中的日期对象获取星期数和年份.

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

直到那时,我还是分开做:我使用isoweek()函数提取week,并使用year()函数提取year.这样我的data.frame有3个变量:日期,星期,年份

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

这是有效的,除了年初/年底:例如,2015年有53个星期,而2016年1月1日属于2015年的第53个星期...但是根据我的代码,它是2016年1月1日是第53周,但是2016年,而我希望是2015年的第53周.

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.

那么R中有没有办法提取在一起有意义的周数和年数?

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.

谢谢!

推荐答案

尝试一下.(两个步骤.)

Try this. (Two steps.)

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

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

有关详细信息,请参见?strptime .

See ?strptime for details.

这篇关于如何在R中从日期获取星期数和年份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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