How to insert the date gap when rbind 2 dataframes with discontinuous date (POSIXct) in r?

Viewed 36

My 2 dataframes look like this:

dput(SB6)
structure(list(shf_htr_resstnc_SB1_1 = c(99.7, 99.7, 99.7, 99.7, 
99.7), shfp_wrnng_SB1_1_1_1_1 = c(NaN, NaN, NaN, NaN, NaN), rDate = structure(c(1650988800, 
1650990600, 1650992400, 1650994200, 1650996000), class = c("POSIXct", 
"POSIXt"), tzone = "")), row.names = 7566:7570, class = "data.frame")
dput(SB6.1)
structure(list(shf_htr_resstnc_SB1_1 = c(99.7, 99.7, 99.7, 99.7, 
99.7), shfp_wrnng_SB1_1_1_1_1 = c(NaN, NaN, NaN, NaN, NaN), rDate = structure(c(1651620600, 
1651622400, 1651624200, 1651626000, 1651627800), class = c("POSIXct", 
"POSIXt"), tzone = "")), row.names = 5:9, class = "data.frame")

I want to rbind both dataframes and insert the time gap between them. SB6 finish on 2022-04-26 18:00:00 and SB6.1 starts at 2022-05-03 22:30:00. Note that the time stamp is 30 in 30 minutes. Between this time gap, the variables should be filled with NaN.

Any help will be much appreciated.

2 Answers

We could bind the datasets and use complete on the sequence from min to max of 'rDate by` an interval of '30 min'

library(dplyr)
library(tidyr)
bind_rows(SB6, SB6.1) %>%
   complete(rDate = seq(min(rDate), max(rDate), by = "30 min"))

You could use full_seq() from tidyr to create the full sequence of datetimes.

library(dplyr)
library(tidyr)

bind_rows(SB6, SB6.1) %>%
  complete(rDate = full_seq(rDate, period = 60*30))
Related