我的预测与移动假期并不完全一致。我想找到一个快速修复:
这是我数据框的结构:
df1:
Date City Visitors WKN WKN_2015 Holiday
2016-11-06 New York 40000 45 46 No_Holiday
2016-11-13 New York 50000 46 47 No_Holiday
2016-11-20 New York 50000 47 48 Thanksgiving
2016-11-27 New York 100000 48 49 Cyber_Monday
2016-12-04 New York 100000 49 50 No_Holiday
2016-12-11 New York 70000 50 51 No_Holiday
.
.
.
2017-11-23 New York 120000 47 47 Thanksgiving
一般情况下,感恩节和网络星期一会有更多的游客来到这个城市。但我的预测并未反映出这一点。现在我想快速修复一下这样的事情:
df1:
Date City Visitors WKN WKN_2015 Holiday New_Visitors
2016-11-06 New York 40000 45 46 No_Holiday 40000
2016-11-13 New York 50000 46 47 No_Holiday 50000
2016-11-20 New York 50000 47 48 Thanksgiving 100000
2016-11-27 New York 100000 48 49 Cyber_Monday 100000
2016-12-04 New York 100000 49 50 No_Holiday 70000
2016-12-11 New York 70000 50 51 No_Holiday 70000
.
.
.
2017-11-23 New York 120000 47 47 Thanksgiving 120000
如果您看到上述数据新的音量仅在感恩节,网络星期一和网络星期一后一周更改。 有没有办法实现自动化,因为2017年的数据仍在继续,依此类推。
我正在考虑快速修复,直到我制定出适合移动假期的预测。有人能指出我正确的方向吗?
我尝试过这样的事情,但这不起作用,因为我只需要3个星期就需要滞后/领先:
df1 <-
df1 %>%
mutate(New_Visitors = ifelse(Holiday == "Thanksgiving", lag(Visitors, (WKN - WKN_2015), Visitors)
逻辑:每年都要寻找感恩节,看看WKN是否匹配。如果不是根据WKN之间的差异从感恩节开始调整未来3周的访客。如果WKN-WKN_2015 == -1然后将访问者引导为接下来的3行,如果WKN-WKN_2015 == 1,那么接下来的3行将访问者滞后1
数据df1 <- structure(list(Date = c("2016-11-06", "2016-11-13", "2016-11-20",
"2016-11-27", "2016-12-04", "2016-12-11", "2017-11-23"), City = structure(c(1L,
1L, 1L, 1L, 1L, 1L, 1L), .Label = "New York", class = "factor"),
Visitors = c(40000L, 50000L, 50000L, 100000L, 100000L, 70000L,
120000L), WKN = c(45L, 46L, 47L, 48L, 49L, 50L, 47L), WKN_2015 = c(46L,
47L, 48L, 49L, 50L, 51L, 47L), Holiday = structure(c(2L,
2L, 3L, 1L, 2L, 2L, 3L), .Label = c("Cyber_Monday", "No_Holiday",
"Thanksgiving"), class = "factor")), .Names = c("Date", "City",
"Visitors", "WKN", "WKN_2015", "Holiday"), row.names = c(NA,
7L), class = "data.frame")
答案 0 :(得分:1)
您每年只有三个星期的兴趣,您可以计算“感恩节”行中的滞后值。我认为不需要dplyr
。
df1$New_Visitors <- df1$Visitors # copy Visitors
ind <- which(df1$Holiday == "Thanksgiving") # get number of "Thanksgiving" rows
invisible(sapply(ind, function(x) {
lag <- df1[x, "WKN_2015"] - df1[x, "WKN"] # calculate the lag
df1[x:(x+2), "New_Visitors"] <<- df1[(x+lag):(x+lag+2), "Visitors"] # rewrite
}))
> df1 # this method treats the three weeks as a unit, so made two NA rows in the example data)
Date City Visitors WKN WKN_2015 Holiday New_Visitors
1 2016-11-06 New York 40000 45 46 No_Holiday 40000
2 2016-11-13 New York 50000 46 47 No_Holiday 50000
3 2016-11-20 New York 50000 47 48 Thanksgiving 100000
4 2016-11-27 New York 100000 48 49 Cyber_Monday 100000
5 2016-12-04 New York 100000 49 50 No_Holiday 70000
6 2016-12-11 New York 70000 50 51 No_Holiday 70000
7 2017-11-23 New York 120000 47 47 Thanksgiving 120000
8 <NA> <NA> NA NA NA <NA> NA
9 <NA> <NA> NA NA NA <NA> NA