R 的新手并且学到了很多东西,我喜欢它。

我的销售数据集有产品、bpid、日期。我想计算相同 bpid 之间的业务差异(不包括周六和周日)。

如果产品或 bpid 更改(或引入新的 bpid/产品),我们需要跳过计算。

    df <- data.frame(product=c('milk','milk','milk','milk','eggs','eggs','eggs','eggs'),
                     bpid=c(400,400,500,500,400,400,500,500),
                     date=c("2016-08-03","2016-08-10","2016-08-04","2016-08-10","2016-08-10","2016-08-16","2016-08-11","2016-08-15"));

df$date <- as.Date(df$date, format = "%Y-%m-%d");

我想要的结果如下所示。 请帮忙....
 product bpid       date    compute-result
   milk  400 2016-08-03      0
   milk  400 2016-08-10      5
   milk  500 2016-08-04      0
   milk  500 2016-08-10      5
   eggs  400 2016-08-10      0
   eggs  400 2016-08-16      4
   eggs  500 2016-08-11      0
   eggs  500 2016-08-15      2

真实数据代码(在结果列中取零)
df <- data.frame(product=c('Keyt','Keyt','Keyt','Keyt','Keyt','Keyt'),
                 bpid=c(30057,30057,30057,30058,30058,30058),
                 date=c("2014-11-21","2015-05-05","2015-05-11","2014-10-16","2014-11-03","2016-03-15"));

df$date <- as.Date(df$date, format = "%Y-%m-%d");

cal <-  Calendar(weekdays=c("saturday", "sunday"))
df$`compute-result` <- 0
idx <- seq(1, nrow(df),2)
df$`compute-result`[idx+1] <- bizdays(df$date[idx], df$date[idx+1], cal)
df

最佳答案

例如:

# install.packages("bizdays")
library(bizdays)
cal <-  create.calendar(name = "mycal", weekdays=c("saturday", "sunday"))
df$`compute-result` <- 0
idx <- seq(1, nrow(df),2)
df$`compute-result`[idx+1] <- bizdays(df$date[idx], df$date[idx+1], cal)
df
#   product bpid       date compute-result
# 1    milk  400 2016-08-03              0
# 2    milk  400 2016-08-10              5
# 3    milk  500 2016-08-04              0
# 4    milk  500 2016-08-10              4
# 5    eggs  400 2016-08-10              0
# 6    eggs  400 2016-08-16              4
# 7    eggs  500 2016-08-11              0
# 8    eggs  500 2016-08-15              2

如果你想按 productbpid 分组,你可以试试
# install.packages("bizdays")
library(bizdays)
cal <-  create.calendar(name="mycal", weekdays=c("saturday", "sunday"))
with(df, ave(as.integer(date), product, bpid, FUN=function(x) {
  x <- as.Date(x, origin="1970-01-01")
  c(0, bizdays(head(x, -1), tail(x, -1), cal))
})) -> df$result
df
#   product  bpid       date result
# 1    Keyt 30057 2014-11-21      0
# 2    Keyt 30057 2015-05-05    117
# 3    Keyt 30057 2015-05-11      4
# 4    Keyt 30058 2014-10-16      0
# 5    Keyt 30058 2014-11-03     12
# 6    Keyt 30058 2016-03-15    356

请注意,在函数内部将 date 转换为 integer 并返回到 Date,否则 ave 会引发错误:

关于r - 计算两个日期之间的工作日,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39260329/

10-12 17:15