Home > OS >  Is there a way in R to add a column for year that understands that there has been a turn of the year
Is there a way in R to add a column for year that understands that there has been a turn of the year

Time:12-01

I have a table that looks like the one below in R. In November 2017, I have forecasted values for December target weeks 50-53 and January weeks 1-4. I wish to add another column called target_year, that contains the year for the forecasted values, as in the table beneath the first table. Is there a way in R to add the correct year in the column?

In the actual data set, I am predicting 30 weeks ahead of time, and from forecast_years = 2015-2020 and forecast_months = 1:12.

I have:

target_week forecast_month forecast_year weekly_level
1 11 2017 0.011
2 11 2017 0.009
3 11 2017 0.011
4 11 2017 0.010
50 11 2017 0.005
51 11 2017 0.005
52 11 2017 0.007
53 11 2017 0.006

I wish to have:

target_week target_year forecast_month forecast_year weekly_level
1 2018 11 2017 0.011
2 2018 11 2017 0.009
3 2018 11 2017 0.011
4 2018 11 2017 0.010
50 2017 11 2017 0.005
51 2017 11 2017 0.005
52 2017 11 2017 0.007
53 2017 11 2017 0.006

CodePudding user response:

Create a logical condition to add the column

library(dplyr)
df1 <- df1 %>%
    mutate(target_year = case_when(target_week < 50 ~ 
       as.integer(forecast_year   1), TRUE ~ forecast_year), .before = 2)

-output

df1
  target_week target_year forecast_month forecast_year weekly_level
1           1        2018             11          2017        0.011
2           2        2018             11          2017        0.009
3           3        2018             11          2017        0.011
4           4        2018             11          2017        0.010
5          50        2017             11          2017        0.005
6          51        2017             11          2017        0.005
7          52        2017             11          2017        0.007
8          53        2017             11          2017        0.006

data

df1 <- structure(list(target_week = c(1L, 2L, 3L, 4L, 50L, 51L, 52L, 
53L), forecast_month = c(11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L
), forecast_year = c(2017L, 2017L, 2017L, 2017L, 2017L, 2017L, 
2017L, 2017L), weekly_level = c(0.011, 0.009, 0.011, 0.01, 0.005, 
0.005, 0.007, 0.006)), class = "data.frame", row.names = c(NA, 
-8L))

CodePudding user response:

I suggest you look into the slider package. It is date aware (to handle things like year ends and inconsistent days in a month) and basically enables forward and backward windowing. Think of the basic case like allowing easy management of rolling sums and averages. Here is an example that creates a rolling window of the current and previous month and executes a function against it. If you are looking at fixed intervals (weeks), look at the block function.

library(slider)
m2 <- slide_index(t$data, t$month, ~ f(.x), identity, .before = ~.x %m-% months(1))
  • Related