简体   繁体   中英

weekend dates within an interval R

I'm trying to identify whether or not a weekend fell within an interval of dates. I've been able to identify if a specific date is a weekend, but not when trying to look at a range of dates. Is this possible? If so, please advise. TIA.

library(lubridate, chron)
start.date <- c("1/1/2017", "2/1/2017")
end.date   <- c("1/21/2017", "2/11/2017")

df <- data.frame(start.date, end.date)

df$start.date <- mdy(df$start.date)
df$end.date   <- mdy(df$end.date)

df$interval.date <- interval(df$start.date, df$end.date)

df$weekend.exist <- ifelse(is.weekend(df$interval.date), 1, 0)
# Error in dts - floor(dts) : 
#   Arithmetic operators undefined for 'Interval' and 'Interval' classes:
#   convert one to numeric or a matching time-span class.

why don't you prefer a seq of dates rather than creating the interval ? like

df$weekend.exist <- sapply(1:nrow(df), function(i) 
                as.numeric(any(is.weekend(seq(df$start.date[i], df$end.date[i],by = "day")))))
# [1] 1 1

library(dplyr)
df %>% 
group_by(start.date,end.date) %>%  
mutate(weekend.exist = as.numeric(any(is.weekend(seq(start.date, end.date,by = "day")))))
#   start.date   end.date weekend.exist
#      <date>     <date>         <dbl>
# 1 2017-01-01 2017-01-21             1
# 2 2017-02-01 2017-02-03             1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM