I use strtoi
to determine the week of year in the following function:
to.week <- function(x) strtoi(format(x, "%W"))
It works fine for most dates:
> to.week(as.Date("2015-01-11"))
[1] 1
However, when I'm trying dates between 2015-02-23
and 2015-03-08
, I get NA
as a result:
> to.week(as.Date("2015-02-25"))
[1] NA
Could you please explain to me what causes the problem?
Here is an implementation that works:
to.week <- function(x) as.integer(format(x, "%W"))
The reason strtoi
fails is by default it tries to interpret numbers as if they were octal when they are preceeded by a "0"
. Since "%W"
returns "08"
, and 8 doesn't exist in octal, you get the NA. From ?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.
Also, you can use:
week(as.Date("2015-02-25"))
Though you may have to offset the result of that by 1 to match your expectations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With