Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing lubridate function to start on Monday rather than Sunday

Tags:

r

lubridate

dates <- NULL

date <- as.Date("01/01/2014","%d/%m/%Y")

dates <- data.frame(date=as.Date(character())
                    ,cal_day_in_year_num = numeric()
                    ,cal_week_id = numeric()
                    ,cal_week_start_date = as.Date(character())
                    ,cal_week_end_date = as.Date(character())
)

for (i in 1:365) {

  dates[i,1] <- date + days(i-1) ## date

  dates[i,2] <- yday(dates[i,1]) ## cal_day_in_year_num

  dates[i,3] <- paste(year(dates[i,1]),sprintf("%02d",week(dates[i,1])),sep="") ## cal_week_id

  dates[i,4] <- floor_date(dates[i,1], "week") ## cal_week_start_date

  dates[i,5] <- ceiling_date(dates[i,1], "week") ## cal_week_end_date

}

View(dates)

For given dates I'm trying to use the lubridate function to calculate the corresponding start and end dates of the week

The issue I'm having is that lubridate is taking the first day of the week to be Sunday, where as I need it to be Monday - does anyone have a way round this?

like image 496
Sam Gilbert Avatar asked Oct 02 '14 11:10

Sam Gilbert


People also ask

How do I get weekday in Lubridate?

wday() returns the day of the week as a decimal number or an ordered factor if label is TRUE .

What does the Lubridate function do?

Description Functions to work with date-times and time-spans: fast and user friendly parsing of date-time data, extraction and updating of components of a date-time (years, months, days, hours, minutes, and seconds), algebraic manipulation on date-time and time-span objects.

Is weekend function in R?

isWeekend: Test for weekends This function takes a vector of dates and returns a logical vector of the same length indicating at each position whether the corresponding date is a weekend in the currently active (global) calendar.


1 Answers

You can make your own functions to do this in base. For example,

start.of.week <- function(date)
  date - (setNames(c(6,0:5),0:6) [strftime(date,'%w')])

end.of.week <- function(date)
  date + (setNames(c(0,6:1),0:6) [strftime(date,'%w')])

start.of.week(as.Date(c('2014-01-05','2014-10-02','2014-09-22','2014-09-27')))
# "2013-12-30" "2014-09-29" "2014-09-22" "2014-09-22"
end.of.week(as.Date(c('2014-01-05','2014-10-02','2014-09-22','2014-09-27')))
# "2014-01-05" "2014-10-05" "2014-09-28" "2014-09-28"
like image 55
nograpes Avatar answered Sep 30 '22 06:09

nograpes