Adding missing rows

前端 未结 3 1638
旧巷少年郎
旧巷少年郎 2020-12-06 03:26

The format of my excel data file is:

 day                 value
 01-01-2000 00:00:00    4
 01-01-2000 00:01:00    3
 01-01-2000 00:02:00    1
 01-01-2000 00:         


        
3条回答
  •  孤城傲影
    2020-12-06 03:50

    I think this is a more general solution, which relies on creating a sequence of all timestamps, using that as the basis for a new data frame, and then filling in your original values in that df where applicable.

    # convert original `day` to POSIX
    ts$day <- as.POSIXct(ts$day, format="%m-%d-%Y %H:%M:%S", tz="GMT")
    
    # generate a sequence of all minutes in a day
    minAsNumeric <- 946684860 + seq(0,60*60*24,by=60) # all minutes of your first day
    minAsPOSIX <- as.POSIXct(minAsNumeric, origin="1970-01-01", tz="GMT") # convert those minutes to POSIX
    
    # build complete dataframe
    newdata <- as.data.frame(minAsPOSIX)
    newdata$value <- ts$value[pmatch(newdata$minAsPOSIX, ts$day)] # fill in original `value`s where present
    newdata$value[is.na(newdata$value)] <- 0 # replace NAs with 0
    

提交回复
热议问题