R - strtoi 奇怪的行为来获得一年中的一周

R - strtoi strange behavior to get week of year

我在以下函数中使用 strtoi 来确定一年中的第几周:

to.week <- function(x) strtoi(format(x, "%W"))

它适用于大多数日期:

> to.week(as.Date("2015-01-11"))
[1] 1

但是,当我尝试 2015-02-232015-03-08 之间的日期时,结果是 NA

> to.week(as.Date("2015-02-25"))
[1] NA

能否请您解释一下导致问题的原因?

这是一个有效的实现:

to.week <- function(x) as.integer(format(x, "%W"))

strtoi 失败的原因是默认情况下,当数字前面有 "0" 时,它会尝试将数字解释为八进制。由于 "%W" returns "08",并且 8 在八进制中不存在,所以你得到了 NA。来自 ?strtoi:

Convert strings to integers according to the given base using the C function strtol, or choose a suitable base following the C rules.

...

For decimal strings as.integer is equally useful.

此外,您可以使用:

week(as.Date("2015-02-25"))

尽管您可能需要将结果偏移 1 以符合您的期望。

您可以像这样稍微修改您的代码

to.week <- function(x) strtoi(format(x, "%W"), 10)

并使用基数 10。