Skip to content

Instantly share code, notes, and snippets.

@mrdwab
Last active December 28, 2015 14:29
Show Gist options
  • Save mrdwab/7515611 to your computer and use it in GitHub Desktop.
Save mrdwab/7515611 to your computer and use it in GitHub Desktop.
Defines a "WeekDays" constant and a "dailyCalendar" function
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)]
}
}
@mrdwab
Copy link
Author

mrdwab commented Nov 21, 2013

@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