Adding missing date values in a data frame with multiple observation periods

前端 未结 4 1916
别那么骄傲
别那么骄傲 2021-01-13 12:39

Thanks in advance.

I am trying to add missing date values that were not included in a observation period for three different individuals.

My data look like t

4条回答
  •  失恋的感觉
    2021-01-13 13:17

    A base R version:

    do.call(rbind,
      by(
        PostData,
        PostData$IndID,
        function(x) {
          out <- merge(
            data.frame(
              IndID=x$IndID[1],
              Date=seq.POSIXt(min(x$Date),max(x$Date),by="1 day")
            ),
            x,
            all.x=TRUE
          )
          out$Event[is.na(out$Event)] <- 0
          out
        }  
      )
    )
    

    Result:

           IndID       Date Event Number Percent
    P01.1    P01 2011-03-04     1      2   0.390
    P01.2    P01 2011-03-05     0     NA      NA
    P01.3    P01 2011-03-06     0     NA      NA
    P01.4    P01 2011-03-07     0     NA      NA
    P01.5    P01 2011-03-08     0     NA      NA
    P01.6    P01 2011-03-09     0     NA      NA
    P01.7    P01 2011-03-10     0     NA      NA
    P01.8    P01 2011-03-11     1      2   0.975
    <>
    

提交回复
热议问题