予測を評価するために使用したいデータセットがあります。データセットは次のようになります。
tibble(article=rep(21,5), estimated_sales=rep(50, 5), week=c(38,39,40,41,42), stock=c(500, 400, 375, 400, 350), purchase=c(0,0,0,50,0))
# A tibble: 5 x 5
article estimated_sales week stock purchase
<dbl> <dbl> <dbl> <dbl> <dbl>
1 21 50 38 500 0
2 21 50 39 400 0
3 21 50 40 375 0
4 21 50 41 400 50
5 21 50 42 350 0
最後に、real_sales
次のように計算された新しい変数を含むデータセットが必要です(たとえば、40週目):375(40週目の在庫)-400(41週目の在庫)+ 50(41週目の購入)= 25、これは、real_sales
40週目の変数の観測値です。
望ましい結果データセットは次のようになります。
# A tibble: 5 x 6
Article estimated_sales week stock purchase rea_sales
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 21 50 38 500 0 100
2 21 50 39 400 0 25
3 21 50 40 375 0 25
4 21 50 41 400 50 100
5 21 50 42 300 0 NA
これは、次を使用して実現できますlead
。
library(dplyr)
df %>% mutate(real_sales = stock - lead(stock) + lead(purchase))
# article estimated_sales week stock purchase real_sales
# <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#1 21 50 38 500 0 100
#2 21 50 39 400 0 25
#3 21 50 40 375 0 25
#4 21 50 41 400 50 50
#5 21 50 42 350 0 NA
とshift
でdata.table
:
library(data.table)
setDT(df)[, real_sales := stock - shift(stock, type = 'lead') +
shift(purchase, type = 'lead')]
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加