[R] getting numeric [0..6] day of week from POSIXct?

John McKown john.archie.mckown at gmail.com
Mon Jul 7 17:54:23 CEST 2014


I have a column, dt, in a data.frame. It is a list of POSIXct objects.
I could use strftime(frame$dt,"%a") to get the day of week as
[sun..sat]. But I need the numeric value in the range of [0..6]. I
can't see a function to do this. I can get it by converting the
POSIXct objects to POSIXlt objects, then extracting the $wday. I don't
know why, but that just doesn't "feel" right to me. What I am actually
trying to do is group my data by Gregorian week (Sunday..Saturday). To
group the data, I am getting the ISO 8601 year and week number using
strftime(dt) with the format of "%G-%V" . But the ISO year&week number
start on Monday, not Sunday. So what I do is:

dt <- as.POSIXlt(frame$dt);
dt <- dt - dt$wday*86400; # 86400 is seconds in a day
frame$groupByWeekNumber <- strftime(dt,"%G-%V");

is there a better way? I have tried my best to find a simpler way.

-- 
There is nothing more pleasant than traveling and meeting new people!
Genghis Khan

Maranatha! <><
John McKown



More information about the R-help mailing list