按名称计算多个组合中两个工作日的差值(start/end)

Calculate the difference between two weekdays in multiple combinations by name(start/end)

这个问题是这个问题的一部分R - Reclassifying days in relation to another variable

对我来说最核心也是最重要的部分是:

假设我们必须使用带有日期名称的列:

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

是否可以计算这两个工作日的差异,其中StartDay始终是起始日:

期望的输出:

  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

思路是StartDay是0,第二天是1,后天是2,...

使用 match 转换为数字,然后将它们相差并取模 7。

wdays <- c("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", 
  "Friday", Saturday")
transform(df, diff = apply(apply(df, 2, match, wdays), 1, diff) %% 7)

给予:

  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

也可以表示为:

transform(df, diff = (match(NextDay, wdays) - match(StartDay, wdays)) %% 7)