Search code examples
rdataframetime-seriesdata-wranglingrandomized-algorithm

How to make monthly data to daily data using random techniques in R


I need to transform this monthly data to daily data by using some randomization technique, for example. Here is the dataframe:


library(dplyr)
library(lubridate)

month_year <- c( 
"08-2021",
"09-2021",
"10-2021",
"11-2021",
"12-2021"
)

monthly_values_var1 <- c(
598,
532,
736,
956,
780
)

monthly_values_var2 <- c(
18.3179,
62.6415,
11.1033,
30.7443,
74.2076
)

df <- data.frame(month_year, monthly_values_var1,  monthly_values_var2) 
df

That is the month dataset view:

And the expected result of this, is something like this:

How to do it using R ?


Solution

  • Like this perhaps?

      df %>%
        mutate(mo_start = dmy(paste(1,month_year))) %>%
        tidyr::uncount(days_in_month(mo_start), .id = "day") %>%
        mutate(date = dmy(paste(day,month_year))) %>%
        mutate(across(contains("var"), ~rnorm(n(), mean = .x, sd = 1)))
    
    # A tibble: 153 x 6
       month_year monthly_values_var1 monthly_values_var2 mo_start     day date      
       <chr>                    <dbl>               <dbl> <date>     <int> <date>    
     1 08-2021                   599.                18.8 2021-08-01     1 2021-08-01
     2 08-2021                   598.                17.4 2021-08-01     2 2021-08-02
     3 08-2021                   596.                18.0 2021-08-01     3 2021-08-03
     4 08-2021                   598.                19.2 2021-08-01     4 2021-08-04
     5 08-2021                   600.                18.3 2021-08-01     5 2021-08-05
     6 08-2021                   597.                19.8 2021-08-01     6 2021-08-06
     7 08-2021                   599.                18.9 2021-08-01     7 2021-08-07
     8 08-2021                   597.                17.9 2021-08-01     8 2021-08-08
     9 08-2021                   597.                16.0 2021-08-01     9 2021-08-09
    10 08-2021                   596.                17.7 2021-08-01    10 2021-08-10
    # … with 143 more rows