R - strtoi weird behavior to get a week of the year

I use strtoi to determine the week of the year in the following function:

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

It works great for most dates:

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

However, when I try to use 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 explain to me the cause of the problem?

+5
source share
2 answers

Here is an implementation that works:

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

The reason strtoi failed - by default, it tries to interpret the numbers as if they were octal when they precede "0" . Since "%W" returns "08" and 8 does not exist in octal, you get NA. From ?strtoi :

Convert strings to integers according to the given base using the strtol C function or select the appropriate base according to the C rules.

...

For decimal strings, as.integer is equally useful.

Alternatively, you can use:

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

Although you may have to compensate for the result by 1 to meet your expectations.

+6
source

you can change your code a little as follows

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

and use base 10.

+4
source

All Articles