Search code examples
rdplyrlubridateposixctseq

How to use seq() to create column of date/times with increments of milliseconds (deciseconds)


My dataframe (df) looks like this:

ID  CH_1   CH_2  CH_3  CH_4             date_time
1 -10096 -11940 -9340 -9972 2018-07-24 10:45:01.1
2 -10088 -11964 -9348 -9960                  <NA>
3 -10084 -11940 -9332 -9956                  <NA>
4 -10088 -11956 -9340 -9960                  <NA>

The last column, date_time is coded as POSIXct format. What I need to do is populate the rest of my dataframe column (it is quite large) with increasing deciseconds, or 100 milliseconds, so that the next column looks like this, and so on...

ID  CH_1   CH_2  CH_3  CH_4             date_time
1 -10096 -11940 -9340 -9972 2018-07-24 10:45:01.1
2 -10088 -11964 -9348 -9960 2018-07-24 10:45:01.2
3 -10084 -11940 -9332 -9956 2018-07-24 10:45:01.3
4 -10088 -11956 -9340 -9960 2018-07-24 10:45:01.4

I have tried using the following,

startDate <- df[["date_time"]][1]
datasetname2$date_time = as.POSIXct(startDate) + seq.POSIXt(datasetname2[6,1], 
units="seconds", by=.1)

but it returns an error (see below)

Error in seq.POSIXt(datasetname2[6, 1], units = "seconds", by = 0.1) :
'from' must be a "POSIXt" object

Solution

  • This might work for you:

    library(lubridate)
    df <- data.frame(ID = 1:4, 
                     CH_1 = rep(c(-10096, -10088, -10084, -10088), 4),
                     CH_2 = rep(c(-11940, -11964, -11940, -11956), 4),
                     date_time = c("2018-07-24 10:45:01.1", rep(NA, 15)))
    
    df$date_time <- as.POSIXct(df$date_time, format= "%F %H:%M:%OS2", tz = "UTC")
    df$date_time <- seq(from = df$date_time[1], to = df$date_time[1] + (nrow(df)-1)*0.1, by = 0.10)
    format(df$date_time, "%OS3")