How to Find Previous Sunday in R

How to find Previous Sunday in R

Here is one approach:

d <-  as.Date("2015-03-18")
prev.days <- seq(d-6,d,by='day')
prev.days[weekdays(prev.days)=='Sunday']
# [1] "2015-03-15"

How to get current week start date ( Monday ) and End Date ( Sunday) in R

You can use lubridate's floor_date and ceiling_date with unit as "week". By default week starts on a Sunday in lubridate so to get start date as Monday we need to add 1 in floor_date.

library(lubridate)
todays_date <- as.Date('2020-07-18')
floor_date(todays_date, 'week') + 1
#[1] "2020-07-13"

ceiling_date(todays_date, 'week')
#[1] "2020-07-19"

How to find next particular day?

Try this function:

nextweekday <- function(date, wday) {
date <- as.Date(date)
diff <- wday - wday(date)
if( diff < 0 )
diff <- diff + 7
return(date + diff)
}

You insert your date and the desired wday (Sunday = 1, Monday = 2, ...) and get the result you wanted.

Find the day of a week

df = data.frame(date=c("2012-02-01", "2012-02-01", "2012-02-02")) 
df$day <- weekdays(as.Date(df$date))
df
## date day
## 1 2012-02-01 Wednesday
## 2 2012-02-01 Wednesday
## 3 2012-02-02 Thursday

Edit: Just to show another way...

The wday component of a POSIXlt object is the numeric weekday (0-6 starting on Sunday).

as.POSIXlt(df$date)$wday
## [1] 3 3 4

which you could use to subset a character vector of weekday names

c("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", 
"Friday", "Saturday")[as.POSIXlt(df$date)$wday + 1]
## [1] "Wednesday" "Wednesday" "Thursday"

How to get week starting date from a date in R

Use the floor_date function from the lubridate package.

library("lubridate")
floor_date(as.Date("04/20/2017", "%m/%d/%Y"), unit="week")

Round date to next weekday in R

A simple solution could be using case_when from dplyr to check if weekday for that day is "Saturday" or "Sunday" and subtract the days accordingly.

library(dplyr)

df %>%
mutate(Day = weekdays(Date),
Date = case_when(Day == "Saturday" ~ Date - 1,
Day == "Sunday" ~ Date - 2,
TRUE ~ Date)) %>%
select(-Day)

# Ticker Date mean_PX_ASK mean_PX_BID Agency
#1 ABNANV 2007-03-02 102.0 102.0 Moody's
#2 ABNANV 2007-03-02 102.0 102.0 Moody's
#3 ABNANV 2007-03-12 102.0 102.0 Moody's
#4 ABNANV 2007-03-12 102.0 102.0 Moody's
#5 ABNANV 2008-09-17 88.9 88.4 Fitch
#6 ABNANV 2008-09-17 88.9 88.4 Fitch

With bizdays we need to create a calendar using create.calendar and default weekdays. We can then use adjust.previous to get the previous working day.

library(bizdays)
cal <- create.calendar("Actual", weekdays=c("saturday", "sunday"))
adjust.previous(df$Date, cal)

#[1] "2007-03-02" "2007-03-02" "2007-03-12" "2007-03-12" "2008-09-17" "2008-09-17"


Related Topics



Leave a reply



Submit