Search code examples
rgraphtime-seriesraw-data

R make timeseries data with raw data


I wanna make Timeseries data with raw data

sample data is

factor date value
fac1 2011-01 10
fac1 2011-05 20
fac1 2011-07 30
fac2 2011-01 40
fac2 2011-03 50

and I wanna make below

fac1 2011-01 10
fac1 2011-02 0
fac1 2011-03 20
fac1 2011-04 0
fac1 2011-05 30

.... it goes to 2011-12

fac2 2011-01 40
fac2 2011-02 0
fac2 2011-03 50
fac2 2011-04 0
fac2 2011-05 0

... it goes to 2011-12

I wanna show this factors by month and draw graph please help me.


Solution

  • We create an expanded dataset the 'factor' and 'date' and then merge with the old dataset

    library(zoo)
    df2 <- merge(expand.grid(factor = unique(df1$factor), 
        date= format(seq(as.Date(paste0(date[1],'-01')), length.out=12, 
              by = '1 month'), "%Y-%m")), df1, all.x = TRUE)
    

    and assign the NA elements in 'value' to 0

    df2$value[is.na(df2$value)] <- 0
    

    Note: No packages used


    Or a similar option with data.table

    library(data.table)
    setDT(df1, key = c('factor', 'date'))
    df1[CJ(factor, date=format(seq(as.Date(paste0(date[1],'-01')), length.out=12, by = '1 month'), 
              format = '%Y-%m'), unique = TRUE)][is.na(value), value := 0][]