This question is part of this question R - Reclassifying days in relation to another variable
The core and most important part for me is this:
Suppose we have to columns with day names:
df <- structure(list(StartDay = c("Friday", "Friday", "Friday", "Thursday",
"Friday", "Friday"), NextDay = c("Wednesday", "Tuesday", "Thursday",
"Wednesday", "Wednesday", "Friday")), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6"))
StartDay NextDay
1 Friday Wednesday
2 Friday Tuesday
3 Friday Thursday
4 Thursday Wednesday
5 Friday Wednesday
6 Friday Friday
Is it possible to calculate the difference of these two weekdays where the StartDay
is always the starting day:
Desired ouptut:
StartDay NextDay difference
1 Friday Wednesday 5
2 Friday Tuesday 4
3 Friday Thursday 6
4 Thursday Wednesday 6
5 Friday Wednesday 5
6 Friday Friday 0
The idea is that StartDay
is 0, the next day is 1, the day after is 2, ...
Use match to convert to numbers and then difference them and take that modulo 7.
wdays <- c("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", Saturday")
transform(df, diff = apply(apply(df, 2, match, wdays), 1, diff) %% 7)
giving:
StartDay NextDay diff
1 Friday Wednesday 5
2 Friday Tuesday 4
3 Friday Thursday 6
4 Thursday Wednesday 6
5 Friday Wednesday 5
6 Friday Friday 0
It could also be expressed as:
transform(df, diff = (match(NextDay, wdays) - match(StartDay, wdays)) %% 7)