Ben
Ben

Reputation: 1522

Convert ts object into a human readable time format

I have two time series

x1<- seq(
     from=as.POSIXct("2020-08-25 18:20:21 CEST", tz="UTC"),
     to=as.POSIXct("2020-08-25 18:41:21 CEST", tz="UTC"),
     by="min"
   )  
x2<- seq(
     from=as.POSIXct("2020-08-25 18:20:46 CEST", tz="UTC"),
     to=as.POSIXct("2020-08-25 18:41:46 CEST", tz="UTC"),
     by="min"
   )  

which I want to combine:

x3<- rbind(x1, x2)
> x3
         [,1]       [,2]       [,3]       [,4]       [,5]       [,6]       [,7]       [,8]       [,9]      [,10]      [,11]      [,12]      [,13]
x1 1598379621 1598379681 1598379741 1598379801 1598379861 1598379921 1598379981 1598380041 1598380101 1598380161 1598380221 1598380281 1598380341
x2 1598379646 1598379706 1598379766 1598379826 1598379886 1598379946 1598380006 1598380066 1598380126 1598380186 1598380246 1598380306 1598380366
        [,14]      [,15]      [,16]      [,17]      [,18]      [,19]      [,20]      [,21]      [,22]
x1 1598380401 1598380461 1598380521 1598380581 1598380641 1598380701 1598380761 1598380821 1598380881
x2 1598380426 1598380486 1598380546 1598380606 1598380666 1598380726 1598380786 1598380846 1598380906

or via

x3<- ts(c(x1, x2),
   start = start(x1),
   frequency = frequency(x1))
> x3
Time Series:
Start = 1 
End = 44 
Frequency = 1 
 [1] 1598379621 1598379681 1598379741 1598379801 1598379861 1598379921 1598379981 1598380041 1598380101 1598380161 1598380221 1598380281 1598380341
[14] 1598380401 1598380461 1598380521 1598380581 1598380641 1598380701 1598380761 1598380821 1598380881 1598379646 1598379706 1598379766 1598379826
[27] 1598379886 1598379946 1598380006 1598380066 1598380126 1598380186 1598380246 1598380306 1598380366 1598380426 1598380486 1598380546 1598380606
[40] 1598380666 1598380726 1598380786 1598380846 1598380906

> is.ts(x3)
[1] TRUE

as you can see, the result is identic but the format differs. rbind results in a numeric format and ts in a time series object. I would like to have it in the same format of x1 and x2 (a POSIXct format) but I can't figure out how. Searching for it is quite difficult because the terms are so numerous in related topics..

edit: Finally, it isn't really about merging x1 and x2 together. Instead, I want to create a POSIXct object beginning with 2020-08-25 18:20:21 CEST and ending with 2020-08-25 18:41:46 CEST but with 30 s time deltas.

Upvotes: 0

Views: 113

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389235

We can create a 30-second sequence from minimum value in x1 and maximum value in x2.

x3 <- seq(min(x1), max(x2), '30 sec')
x3
# [1] "2020-08-25 18:20:21 UTC" "2020-08-25 18:20:51 UTC" "2020-08-25 18:21:21 UTC"
# [4] "2020-08-25 18:21:51 UTC" "2020-08-25 18:22:21 UTC" "2020-08-25 18:22:51 UTC"
# [7] "2020-08-25 18:23:21 UTC" "2020-08-25 18:23:51 UTC" "2020-08-25 18:24:21 UTC"
#[10] "2020-08-25 18:24:51 UTC" "2020-08-25 18:25:21 UTC" "2020-08-25 18:25:51 UTC"
#...

Upvotes: 1

Related Questions