Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - strtoi strange behavior to get week of year

Tags:

date

format

r

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?

like image 724
paljenczy Avatar asked May 06 '15 15:05

paljenczy


1 Answers

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.

like image 86
BrodieG Avatar answered Sep 28 '22 03:09

BrodieG