rbind for datetime

Here,
I am trying to insert 30 min interval for each time step using for loop.
Everything looks okay. However, the last step of rbind has changed the format.
Could anyone check this out?
Thanks

df <- as.POSIXct(c("2030-01-01 00:00:00", "2030-01-01 01:00:00",
                 "2030-01-01 02:00:00", "2030-01-01 03:00:00"), 
                 format="%Y-%m-%d %H:%M:%S")

t=NULL;
for (i in 1:length(df)){
  t1=df[i]
  t2=t1+(30*60)
 t=rbind(t,t1,t2)
 }
t

lubridate can help you doing that the vector way

df <- as.POSIXct(c("2030-01-01 00:00:00", "2030-01-01 01:00:00",
                   "2030-01-01 02:00:00", "2030-01-01 03:00:00"), 
                 format="%Y-%m-%d %H:%M:%S")

library(lubridate)
#> 
#> Attachement du package : 'lubridate'
#> The following objects are masked from 'package:base':
#> 
#>     date, intersect, setdiff, union
df + minutes(30)
#> [1] "2030-01-01 00:30:00 CET" "2030-01-01 01:30:00 CET"
#> [3] "2030-01-01 02:30:00 CET" "2030-01-01 03:30:00 CET"

Created on 2020-08-14 by the reprex package (v0.3.0)

1 Like

Thanks @cderv for your prompt reply.
In addition to this, I do want to have the input df as well as the 30-min.
So, there will be 8 output that comes in sequence. can you check on this?

Here is one way to do it using @cderv's method.

df <- as.POSIXct(c("2030-01-01 00:00:00", "2030-01-01 01:00:00",
                   "2030-01-01 02:00:00", "2030-01-01 03:00:00"), 
                 format="%Y-%m-%d %H:%M:%S")
library(lubridate)

dfNew <- df + minutes(30)
df <- sort(c(df, dfNew))
df
#> [1] "2030-01-01 00:00:00 MST" "2030-01-01 00:30:00 MST"
#> [3] "2030-01-01 01:00:00 MST" "2030-01-01 01:30:00 MST"
#> [5] "2030-01-01 02:00:00 MST" "2030-01-01 02:30:00 MST"
#> [7] "2030-01-01 03:00:00 MST" "2030-01-01 03:30:00 MST"

Created on 2020-08-14 by the reprex package (v0.3.0)

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.