我试图从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",…,
通过使用seq。函数,我只得到星期一。我使用的第二种方法是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
(缩写或完整的工作日名称)的一个优点是它们容易受到地区/语言变化的影响,而%w
总是整数。
请参阅?strptime
以获得有关%
-代码用于格式化的更多讨论。