Converting Monthly Data to Daily in R

前端 未结 5 1001
慢半拍i
慢半拍i 2021-01-18 08:02

I have a data.frame df that has monthly data:

Date           Value 
2008-01-01      3.5          
2008-02-01      9.5          
2008-03-01      0.1                   


        
5条回答
  •  时光说笑
    2021-01-18 08:59

    to.daily can only be applied to xts/zooobjects and can only convert to a LOWER frequency. i.e. from daily to monthly, but not the other way round. One easy way to accomplish what you want is converting df to an xts object:

    df.xts <- xts(df$Value,order.by = df$Date)
    

    And merge, like so:

    na.locf(merge(df.xts, foo=zoo(NA, order.by=seq(start(df.xts), end(df.xts),
      "day",drop=F)))[, 1])
                   df.xts
    2018-01-01    3.5
    2018-01-02    3.5
    2018-01-03    3.5
    2018-01-04    3.5
    2018-01-05    3.5
    2018-01-06    3.5
    2018-01-07    3.5
    ….
    2018-01-27    3.5
    2018-01-28    3.5
    2018-01-29    3.5
    2018-01-30    3.5
    2018-01-31    3.5
    2018-02-01    9.5
    2018-02-02    9.5
    2018-02-03    9.5
    2018-02-04    9.5
    2018-02-05    9.5
    2018-02-06    9.5
    2018-02-07    9.5
    2018-02-08    9.5
    ….
    2018-02-27    9.5
    2018-02-28    9.5
    2018-03-01    0.1
    

    If you want to adjust the price continuously over the course of a month use na.spline in place of na.locf.

提交回复
热议问题