How to add only missing Dates in Dataframe

后端 未结 3 846
别那么骄傲
别那么骄傲 2020-12-11 18:48

I have below mentioned data frame:

Date        Val1     Val2
2018-04-01  125      0.05
2018-04-03  458      2.99
2018-04-05  354      1.25

3条回答
  •  猫巷女王i
    2020-12-11 19:36

    You could use padr. padr is made for filling in missing date values. First you add the missing dates based on the interval, and if you do not want NA's you fill them with a value (or function of most occuring value)

    edit: added end_val to include the run until sys.Date()

    library(padr)
    # Specify end_val to go all the way to sys.Date and add 1 to include sys.Date
    padded_df <- pad(df, interval = "day", end_val = Sys.Date()+1)
    padded_df <- fill_by_value(padded_df, value = 0)
    padded_df
    
            Date Val1 Val2
    1 2018-04-01  125 0.05
    2 2018-04-02    0 0.00
    3 2018-04-03  458 2.99
    4 2018-04-04    0 0.00
    5 2018-04-05  354 1.25
    .....
    
    31 2018-05-01    0    0
    32 2018-05-02    0    0
    33 2018-05-03    0    0
    34 2018-05-04    0    0
    35 2018-05-05    0    0
    36 2018-05-06    0    0
    

提交回复
热议问题