简体   繁体   English

将星期数转换为日期,将星期数添加到今天的日期

[英]Convert week number to date keeps adding week number to today's date

Sorry, this has been asked multiple times but none of the posted replies have worked for me. 抱歉,已被多次询问,但没有任何回复对我有用。 I am trying to convert week number to date or ideally a month name using as.Date function. 我正在尝试使用as.Date函数将周号转换为日期或理想的月份名称。 However I keep getting the same result no matter what week I put in and I just cannot figure out why. 但是,无论我在哪个星期都可以得到相同的结果,而我却无法弄清楚为什么。 Any help is appreciated 任何帮助表示赞赏

```R
as.Date(x = 03, format = "%W",origin = "2019-01-01")
# This results in "2019-09-16"

as.Date(x = 4, format = "%W",origin = "2019-01-01")
# This results in "2019-09-17"

as.Date(x = 12, format = "%w",origin = "2019-01-01")
# This results in "2019-09-25"

as.Date(x = 12, format = "%W",origin = "2018-01-01")
# This results in "2019-09-25"
```

Even when I change the year, it produces the same output. 即使我更改年份,它也会产生相同的输出。 It seems to be adding today's date (13th) to the week number. 似乎是将今天的日期(第13个)添加到星期数中。 The most frustrating part is that this is an old code, which has been working perfectly as of yesterday 最令人沮丧的是,这是一个旧代码,到昨天为止,它一直运行良好

From the help: "If the date string does not specify the date completely, the returned answer may be system-specific. The most common behavior is to assume that a missing year, month or day is the current one." 从帮助中:“如果日期字符串未完全指定日期,则返回的答案可能是特定于系统的。最常见的行为是假定缺少的年,月或日为当前年份。”

The easiest way to get around this is to specify the day and then convert: 解决此问题的最简单方法是指定日期,然后进行转换:

 as.Date(x = paste(3, "0"), format = "%W %w")
[1] "2019-01-15"

 as.Date(x = paste(10, "0"), format = "%W %w")
[1] "2019-03-04"

You will also need to specify the year, if you change it from the current year. 如果从当前年份更改年份,则还需要指定年份。

as.Date(x = paste(10, "0 2018"), format = "%W %w %Y")
[1] "2018-03-04"

You can substitute in your vector in for the 3 or 10 in the above examples. 您可以用向量代替上述示例中的3或10。

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

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