zchen
zchen

Reputation: 77

How to count weekdays between two data.frame columns(fields) in R

eg. df got 2 columns named as c("Today", "Expiration"). I want to get a new field as "Workdays". But I failed when I wrote like this:

Today <- seq.Date(as.Date("2015-10-01"), as.Date("2015-10-11"), by = "days")
Expiration <- seq.Date(as.Date("2015-10-20"), as.Date("2015-10-30"), by = "day")

df <- data.frame(Today, Expiration)

df <- transform(df, Workdays = sum(!weekdays(seq.Date(Today, Expiration, "days")) %in% c("Saturday", "Sunday")))

Error in seq.Date(Today, Expiration, "days") : 'from' must be of length 1

The warning is "Today" should be length of 1.

Please help me out, thank you!

Maybe calculate directly works better

d <- with(df, Expiration - Today)
d <- as.numeric(d)
Workdays <- d - ((d - 1) %/% 7 ) * 2 - ifelse(d %% 7 == 0, 2, ifelse(d %% 7 == 6, 1, 0)

Upvotes: 1

Views: 326

Answers (1)

akrun
akrun

Reputation: 886998

We can use data.table. We can convert the 'data.frame' to 'data.table' (setDT(df), grouped by sequence of rows (1:nrow(df)), we get the sum of the logical condition and assign (:=) that as new column ('Workdays').

library(data.table)
setDT(df)[, Workdays:=sum(!weekdays(seq(Today, Expiration, by = 'day')) %in% 
                         c('Saturday', 'Sunday')) , 1:nrow(df)]

Upvotes: 1

Related Questions