[英]R: Get correct week number from date (beginning/end of year)
I struggle with getting my code correct.我很难让我的代码正确。 From my dataset I want to assign 'year+week' to all the dates but have not succeeded.
从我的数据集中,我想将“年+周”分配给所有日期,但没有成功。 The output I get is displayed below:
我得到的output如下图所示:
referenceTime![]() |
Week![]() |
---|---|
31-12-2020 ![]() |
2020 - W53 ![]() |
... ![]() |
... ![]() |
01-01-2017 ![]() |
2017 - W52 ![]() |
01-01-2017 is in week 52 in 2016, and not 2017. It looks like a lot of other users also have difficulties with R not registrering beginning and ending of years, so the weeks get wrong. 01-01-2017 是在 2016 年的第 52 周,而不是 2017 年。看起来很多其他用户也遇到了 R 没有注册年份的开始和结束的问题,所以几周会出错。 I have looked at other responses on StackOverflow but have not succeeded to find something that works for my code.
我查看了 StackOverflow 上的其他回复,但没有成功找到适用于我的代码的内容。 The code I have now is this:
我现在的代码是这样的:
data$Week <- format(df2$referenceTime, format="%YW%V")
I am open for other suggestions, I see that some also use the lubridate
package.我愿意接受其他建议,我看到有些人还使用
lubridate
。
Hope someone can help me with this issue.希望有人可以帮助我解决这个问题。
You can use %G
The week-based year instead of %Y
:您可以使用
%G
基于周的年份而不是%Y
:
format(x, format="%G-%V")
#[1] "2020-53" "2016-52"
Or use %U
instead of %V
:或使用
%U
而不是%V
:
format(x, format="%Y-%U")
#[1] "2020-52" "2017-01"
Data:数据:
x <- as.Date(c("2020-12-31", "2017-01-01"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.