0
votes

I would like to compare 2 time series by their time of day. These 2 series are from different dates (ie, 2018-08-10 for the first series and 2018-09-10 for the second series) but have the same time stamps. Is it possible to do a cbind/merge between the 2 series only taking in to acccount the timestamps but not the date of the time stamp?

Thanks

1

1 Answers

0
votes

I have no idea of how your data looks like, so next time please create a reproducible exampel. I created 2 data.frames that can serve as an example. You should now that xts needs a valid timeseries object and an hms timeseries is not a valid timeseries for xts.

That being said, you can always transform an xts object into a data.frame with:

my_df <- data.frame(times = index(my_xts), coredata(my_xts))

Now for the example:

I'm showing it via dplyr, but merge will work as well if you create a hms object in each data.frame. I'm using as.hms from the hms package to create a hms object in the data.frames and join them together.

x <- Sys.time() + 1:10*60 # today
y <- x - 60*60*24 # same time yesterday

df1 <- data.frame(times = x, val1 = 1:10)
df2 <- data.frame(times = y, val2 = 10:1)

library(dplyr)

# create hms object in df1 and in df2 on the fly
df1 %>% 
  mutate(times2 = hms::as.hms(times)) %>% 
  inner_join(df2 %>% mutate(times2 = hms::as.hms(times)), by = "times2"
             )

               times.x val1          times2             times.y val2
1  2018-10-01 18:26:05    1 18:26:05.421764 2018-09-30 18:26:05   10
2  2018-10-01 18:27:05    2 18:27:05.421764 2018-09-30 18:27:05    9
3  2018-10-01 18:28:05    3 18:28:05.421764 2018-09-30 18:28:05    8
4  2018-10-01 18:29:05    4 18:29:05.421764 2018-09-30 18:29:05    7
5  2018-10-01 18:30:05    5 18:30:05.421764 2018-09-30 18:30:05    6
6  2018-10-01 18:31:05    6 18:31:05.421764 2018-09-30 18:31:05    5
7  2018-10-01 18:32:05    7 18:32:05.421764 2018-09-30 18:32:05    4
8  2018-10-01 18:33:05    8 18:33:05.421764 2018-09-30 18:33:05    3
9  2018-10-01 18:34:05    9 18:34:05.421764 2018-09-30 18:34:05    2
10 2018-10-01 18:35:05   10 18:35:05.421764 2018-09-30 18:35:05    1