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)]
}
}
@nograpes
Copy link

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.

@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