Converting Monthly Data to Daily in R

前端 未结 5 1052
慢半拍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:40

    Not sure if i understood perfectly but i think something like this may work.

    First, i define the monthly data table

    library(data.table)
    
    DT_month=data.table(Date=as.Date(c("2008-01-01","2008-02-01","2008-03-01","2008-05-01","2008-07-01"))
                  ,Value=c(3.5,9.5,0.1,5,8))
    

    Then, you have to do the following

    DT_month[,Month:=month(Date)]
    DT_month[,Year:=year(Date)]
    
    start_date=min(DT_month$Date)
    end_date=max(DT_month$Date)
    
    DT_daily=data.table(Date=seq.Date(start_date,end_date,by="day"))
    DT_daily[,Month:=month(Date)]
    DT_daily[,Year:=year(Date)]
    DT_daily[,Value:=-100]
    
    for( i in unique(DT_daily$Year)){
      for( j in unique(DT_daily$Month)){
        if(length(DT_month[Year==i & Month== j,Value])!=0){
          DT_daily[Year==i & Month== j,Value:=DT_month[Year==i & Month== j,Value]]
        }
      }
    }
    

    Basically, the code will define the month and year of each monthly value in separate columns.

    Then, it will create a vector of daily data using the minimum and maximum dates in your monthly data, and will create two separate columns for year and month for the daily data as well.

    Finally, it goes through every combination of year and months of data filling the daily values with the monthly ones. In case there is no data for certain combination of month and year, it will show a -100.

    Please let me know if it works.

提交回复
热议问题