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

David L Carlson dcarlson at tamu.edu
Mon Jul 7 18:08:51 CEST 2014


?format.POSIXct

Particularly %w

> x <- Sys.time()
> as.numeric(format(x, "%w"))
[1] 1

-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of John McKown
Sent: Monday, July 7, 2014 10:54 AM
To: r-help
Subject: [R] getting numeric [0..6] day of week from POSIXct?

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

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list