如何在 r 中创建一系列显示星期一和星期日的周间隔?

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

我正在尝试获取从 2018-09-03 到 2021-03-23 的序列周间隔,仅显示星期一和星期日。我会得到结果 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"

通过使用序列。功能我只得到星期一。我使用的第二种方法是 Map(c, dates_ranges[-length(dates_ranges)], dates_ranges[-1]) 但是我有间隔序列作为数字 你能帮帮我吗?

`

 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])

`

您可以创建所有日期序列并进行过滤以仅保留星期日和星期一。

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"
#...
#...

然后您可以将数据集分成两组。

split(selected_dates, ceiling(seq_along(selected_dates)/2))

#$`1`
#[1] "2018-09-03" "2018-09-09"

#$`2`
#[1] "2018-09-10" "2018-09-16"

#$`3`
#[1] "2018-09-17" "2018-09-23"
#...
#...

使用 format(., format="%w") 查找工作日是 0(星期日)还是 1(星期一)。

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"

%w 优于 %a%A(缩写或完整的工作日名称)的一个优点是它们易于 locale/language 更改,而 %w 总是整数。

有关 % 格式化代码的更多讨论,请参阅 ?strptime