I have 100 text files which contains time series starting and ending at different point of times. I want to extract the values for common period of time in the series. Use the following code to generate the sample data:
set.seed(1)
D1 = data.frame(time = seq(ISOdatetime(2012, 6, 26, 3, 15, 00),
length = 500, by = 900),
value = rnorm(500))
D2 = data.frame(time = seq(ISOdatetime(2012, 6, 24, 5, 30, 00),
length = 541, by = 900),
value = rnorm(541))
D3 = data.frame(time = seq(ISOdatetime(2012, 6, 23, 5, 45, 00),
length = 700, by = 900),
value = rnorm(700))
This data will give you 3 time series starting and ending and different times. I wish to keep only the values for common time period and remove the rest. ie if,
Then I wish to keep the data of intersection of the three time series ie data corresponding to:-
I searched SO and other websites but didn't find any solution. Need help on that. How do I achieve that?
It seems like you need to familiarize yourself with the xts
package. Convert your data frame to xts
time series objects and use merge
. merge
will merge all values, so if you want values occurring in all, you can also use na.omit
.
require(xts)
D1 = xts(d1$Value, d1$Time)
D2 = xts(d2$Value, d2$Time)
D3 = xts(d3$Value, d3$Time)
temp = merge(D1, D2, D3)
Here is some example output. For head
and tail
, note the presence of NA
values.
head(temp)
# D1 D2 D3
# 2012-06-26 13:15:19 -0.50219235 NA NA
# 2012-06-26 13:30:19 0.13153117 NA NA
# 2012-06-26 13:45:19 -0.07891709 NA NA
# 2012-06-26 14:00:19 0.88678481 NA NA
# 2012-06-26 14:15:19 0.11697127 NA NA
# 2012-06-26 14:30:19 0.31863009 NA NA
tail(temp)
# D1 D2 D3
# 2012-07-04 05:45:19 NA NA 1.4799645
# 2012-07-04 06:00:19 NA NA -0.3942801
# 2012-07-04 06:15:19 NA NA -0.6767234
# 2012-07-04 06:30:19 NA NA -0.2425192
# 2012-07-04 06:45:19 NA NA 0.4547177
# 2012-07-04 07:00:19 NA NA 1.1712661
head(na.omit(temp))
# D1 D2 D3
# 2012-06-27 14:15:19 -0.3329234 -1.63230970 0.75619287
# 2012-06-27 14:30:19 1.3631137 -0.06299626 -1.36131851
# 2012-06-27 14:45:19 -0.4691473 -0.70544686 -0.60876462
# 2012-06-27 15:00:19 0.8428756 -0.31417818 -0.21174696
# 2012-06-27 15:15:19 -1.4579937 -0.26694627 -0.67847242
# 2012-06-27 15:30:19 -0.4003059 0.15315947 0.06665787
tail(na.omit(temp))
# D1 D2 D3
# 2012-07-01 16:45:19 -0.49419020 1.1911322 2.73143169
# 2012-07-01 17:00:19 -1.71111303 0.7613245 0.57057667
# 2012-07-01 17:15:19 0.04005805 -0.1210687 1.32083870
# 2012-07-01 17:30:19 -0.56114348 -1.2250590 0.09951626
# 2012-07-01 17:45:19 -2.55736206 -0.1637461 -0.39435301
# 2012-07-01 18:00:19 -0.69677881 -1.3138963 0.63649492
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.