Home > Enterprise >  How to create a sequence of week intervals showing the monday and sunday in r?
How to create a sequence of week intervals showing the monday and sunday in r?

Time:10-17

I am trying to get a sequence week interval from 2018-09-03 to 2021-03-23 showing only Monday and Sunday. I would get as result dates_ranges.

dates_ranges=c("2018-09-03 2018-09-09", "2018-09-10 2018-09-16", "2018-09-17 2018-09-23", ... , "2021-03-22 2021-03-28"

By using the seq. function I get only the Mondays. A second approach I used was Map(c, dates_ranges[-length(dates_ranges)], dates_ranges[-1]) but Than I have seqence of intervals as a numeric Could u please help me?

`

 startdate <- as.Date("2018-09-03")
  enddate <- as.Date("2021-03-22")

 #first approach
 dates_ranges<- seq.Date(from= (startdate),to=enddate, by= 
 "week")

  #second approach 
  dates_ranges<- as.numeric(dates_ranges)
  weeklyinterval<-Map(c, dates_ranges[-length(dates_ranges)], 
  dates_ranges[-1])

`

CodePudding user response:

You can create all the dates sequences and filter to keep only Sundays and Mondays.

start_date <- as.Date('2018-09-03')
end_date <- as.Date('2021-03-23')
all_dates <- seq(start_date, end_date, by = 'day')
selected_dates <- all_dates[weekdays(all_dates) %in% c('Monday', 'Sunday')]
selected_dates

# [1] "2018-09-03" "2018-09-09" "2018-09-10" "2018-09-16" "2018-09-17"
# [6] "2018-09-23" "2018-09-24" "2018-09-30" "2018-10-01" "2018-10-07"
#[11] "2018-10-08" "2018-10-14" "2018-10-15" "2018-10-21" "2018-10-22"
#...
#...

CodePudding user response:

Use format(., format="%w") to find which weekdays are 0 (Sunday) or 1 (Monday).

dates_ranges <- seq.Date(as.Date("2021-09-03"), as.Date("2021-10-23"), by = "day")
dates_ranges
#  [1] "2021-09-03" "2021-09-04" "2021-09-05" "2021-09-06" "2021-09-07" "2021-09-08" "2021-09-09" "2021-09-10" "2021-09-11"
# [10] "2021-09-12" "2021-09-13" "2021-09-14" "2021-09-15" "2021-09-16" "2021-09-17" "2021-09-18" "2021-09-19" "2021-09-20"
# [19] "2021-09-21" "2021-09-22" "2021-09-23" "2021-09-24" "2021-09-25" "2021-09-26" "2021-09-27" "2021-09-28" "2021-09-29"
# [28] "2021-09-30" "2021-10-01" "2021-10-02" "2021-10-03" "2021-10-04" "2021-10-05" "2021-10-06" "2021-10-07" "2021-10-08"
# [37] "2021-10-09" "2021-10-10" "2021-10-11" "2021-10-12" "2021-10-13" "2021-10-14" "2021-10-15" "2021-10-16" "2021-10-17"
# [46] "2021-10-18" "2021-10-19" "2021-10-20" "2021-10-21" "2021-10-22" "2021-10-23"
dates_ranges[format(dates_ranges, format="%w") %in% 0:1]
#  [1] "2021-09-05" "2021-09-06" "2021-09-12" "2021-09-13" "2021-09-19" "2021-09-20" "2021-09-26" "2021-09-27" "2021-10-03"
# [10] "2021-10-04" "2021-10-10" "2021-10-11" "2021-10-17" "2021-10-18"

An advantage of %w over %a or %A (abbreviated or full weekday name) is that those are prone to locale/language changes, whereas %w is always integer.

See ?strptime for more discussion about the %-codes for formatting.

  • Related