Last active
December 28, 2015 14:29
-
-
Save mrdwab/7515611 to your computer and use it in GitHub Desktop.
Defines a "WeekDays" constant and a "dailyCalendar" function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
WeekDays <- function(startOn = "Monday", abbreviate = FALSE) { | |
WD <- c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday") | |
x <- match(startOn, WD) | |
WD <- WD[c(x:7, setdiff(1:7, x:7))] | |
if (isTRUE(abbreviate)) { | |
substring(WD, 0, 3) | |
} else WD | |
} | |
dailyCalendar <- function(startDate = Sys.Date(), days = 30, startOn = "Monday", fancy = FALSE) { | |
require(reshape2) | |
inDailyTs <- ts(as.character(seq(as.Date(startDate), | |
length.out = days, by = 1)), | |
frequency = 7) | |
temp <- data.frame( | |
weekday = factor(weekdays(as.Date(as.character(inDailyTs))), WeekDays(startOn)), | |
date = inDailyTs, | |
month = format(as.Date(as.character(inDailyTs)), "%B"), | |
day = format(as.Date(as.character(inDailyTs)), "%d"), | |
year = format(as.Date(as.character(inDailyTs)), "%Y"), | |
stringsAsFactors = FALSE) | |
temp$week <- cumsum(temp$weekday == startOn) | |
if (isTRUE(fancy)) { | |
A <- paste(temp$month, temp$year) | |
X <- split(temp, factor(A, unique(A), ordered=TRUE)) | |
lapply(X, function(y) { | |
dcast(y, week ~ weekday, value.var = "day", fill = "", drop=FALSE)[WeekDays(startOn)] | |
}) | |
} else { | |
dcast(temp, week ~ weekday, value.var = "date", fill = "")[WeekDays(startOn)] | |
} | |
} |
There is also a "fancy" view for dailyCalendar
:
dailyCalendar(startDate="2013-12-27", days=30, startOn="Friday", fancy=TRUE)
# $`December 2013`
# Friday Saturday Sunday Monday Tuesday Wednesday Thursday
#1 27 28 29 30 31
#
# $`January 2014`
# Friday Saturday Sunday Monday Tuesday Wednesday Thursday
#1 01 02
#2 03 04 05 06 07 08 09
#3 10 11 12 13 14 15 16
#4 17 18 19 20 21 22 23
#5 24 25
It might be interesting to modify the Weekdays
function so that it returns weekdays in the language of the locale. I think this would do it.
WD<-strftime(seq(as.Date('2013-11-18'),(as.Date('2013-11-18')+6),by=1),'%A')
But then startsOn
would have to modified to either be an integer, and to handle if the user inputs a day of week in a non-English language.
@nograpes, I thought about that but I have not had much time to look into how locale settings work in R. I'll check out your suggestion when I have some time.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Examples
WeekDays
simply defines a character constant of the (English) weekday names, optionally abbreviated, and starting on an arbitrary day of the week (defaulting with starting on "Monday").dailyCalendar
creates a calendar view of a range of daily dates.