在R中使用循环列表计算交货期内的天数

elcex8rz  于 2023-05-26  发布在  其他
关注(0)|答案(3)|浏览(122)

在R中创建循环列表
我正在使用一个交付时间表,我需要计算每个唯一交付期的天数。我本来想在Excel中解决我的相关问题,但现在我想我需要使用R来代替。
如果我有一周的日期列表:

DaysOfWeek <- list("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday")

我总是希望能够参考列表并计算未来的天数。
例如,如果交货计划为交货期1:星期五至星期一,第二阶段:是周二到周四我希望能够引用我的列表,比如交货日1是星期五,向前计数直到下一个交货日,星期二,并查看在此期间有四个交货日。
我已经尝试过努力编码特定的日期,并将它们设置为一周中的几天,以及几个不同的for循环,现在仍然在挣扎。

nxagd54h

nxagd54h1#

如果我明白你的意思,我们可以用模运算。
我会将一周中的每一天编码为一个从0开始的命名向量,然后使用一个小助手函数来计算差值mod 7。

days = c(
  Monday = 0,
  Tuesday = 1,
  Wednesday = 2,
  Thursday = 3,
  Friday = 4,
  Saturday = 5,
  Sunday = 6
)

day_diff = function(from, to) {
  unname((days[to] - days[from]) %% 7)
}

day_diff("Friday", "Tuesday")
# [1] 4 

day_diff("Saturday", "Sunday")
# [1] 1

day_diff("Sunday", "Saturday")
# [1]  6
2jcobegt

2jcobegt2#

您可以执行以下操作:

DaysOfWeek <- c("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday")

delivery_start <- 'Sunday'
delivery_end <- 'Tuesday'

delivery_days <- ifelse(which(DaysOfWeek == delivery_start) > which(DaysOfWeek == delivery_end),
                        7 + which(DaysOfWeek == delivery_end) - which(DaysOfWeek == delivery_start),
                        which(DaysOfWeek == delivery_end) - which(DaysOfWeek == delivery_start))

这个例子将返回结果2

2g32fytz

2g32fytz3#

这里有一种可能性,你可以将一周中的天数向量加倍,然后找到两天之间的最短正距离:

DayofWeek <- rep(c("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"), 2)

days_between <- function(day1, day2) {
  start <- which(DayofWeek == day1)
  end <- which(DayofWeek == day2)
  
  min(Filter(\(x) x > 0, sapply(end, `-`, start)))
}

输出

days_between("Monday", "Saturday")
[1] 5
days_between("Sunday", "Monday")
[1] 1

相关问题