1

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, ...

TarJae
  • 72,363
  • 6
  • 19
  • 66
  • Do we assume that `NextDay` is always between 1 and 7 days later than `StartDay` ? So in your example when both days are Friday, the second Friday is 7 days later? – neilfws Feb 14 '22 at 22:46
  • yes always bewteen 1 and 7. – TarJae Feb 14 '22 at 22:47
  • But the difference in your example data where both days are Friday is 0. Should that be 7 ? – neilfws Feb 14 '22 at 22:53
  • OK if the day is same then it is 0 e.g friday to friday = 0. friday to saturday = 1, .. friday to thursday = 6. Or Thursday to thursday = 0 and so on. I know what you mean. Thanks for clarification. In other words the maximum difference is 6 not 7! – TarJae Feb 14 '22 at 22:57

1 Answers1

1

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)
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341