Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Parse Year + Week Number in R?

Tags:

datetime

r

Is there a good way to get a year + week number converted a date in R? I have tried the following:

> as.POSIXct("2008 41", format="%Y %U")
[1] "2008-02-21 EST"
> as.POSIXct("2008 42", format="%Y %U")
[1] "2008-02-21 EST"

According to ?strftime:

%Y Year with century. Note that whereas there was no zero in the original Gregorian calendar, ISO 8601:2004 defines it to be valid (interpreted as 1BC): see http://en.wikipedia.org/wiki/0_(year). Note that the standard also says that years before 1582 in its calendar should only be used with agreement of the parties involved.

%U Week of the year as decimal number (00–53) using Sunday as the first day 1 of the week (and typically with the first Sunday of the year as day 1 of week 1). The US convention.

like image 963
Kyle Brandt Avatar asked Feb 21 '12 15:02

Kyle Brandt


People also ask

How do you calculate week number from date?

To determine how many weeks elapsed between two dates, we can use a simple formula to find the number of days between the dates, then divide by 7. The formula will return a decimal number.


1 Answers

This is kinda like another question you may have seen before. :)

The key issue is: what day should a week number specify? Is it the first day of the week? The last? That's ambiguous. I don't know if week one is the first day of the year or the 7th day of the year, or possibly the first Sunday or Monday of the year (which is a frequent interpretation). (And it's worse than that: these generally appear to be 0-indexed, rather than 1-indexed.) So, an enumerated day of the week needs to be specified.

For instance, try this:

as.POSIXlt("2008 42 1", format = "%Y %U %u")

The %u indicator specifies the day of the week.

Additional note: See ?strptime for the various options for format conversion. It's important to be careful about the enumeration of weeks, as these can be split across the end of the year, and day 1 is ambiguous: is it specified based on a Sunday or Monday, or from the first day of the year? This should all be specified and tested on the different systems where the R code will run. I'm not certain that Windows and POSIX systems sing the same tune on some of these conversions, hence I'd test and test again.

like image 178
Iterator Avatar answered Sep 21 '22 15:09

Iterator