Reputation: 675
Suppose I have two time series
(x <- xts(c(5,4:10), Sys.Date()+3:10))
(y <- xts(1:6, Sys.Date()+1:6))
merge(x,y)
x y
2018-04-20 NA 1
2018-04-21 NA 2
2018-04-22 5 3
2018-04-23 4 4
2018-04-24 5 5
2018-04-25 6 6
2018-04-26 7 NA
2018-04-27 8 NA
2018-04-28 9 NA
2018-04-29 10 NA
How do I get a time series that takes the value of y
if it is present, but falls back to x
only if y
does not have a value at a particular date? For example, I want the values in z
as below:
x y z
2018-04-20 NA 1 1
2018-04-21 NA 2 2
2018-04-22 5 3 3
2018-04-23 4 4 4
2018-04-24 5 5 5
2018-04-25 6 6 6
2018-04-26 7 NA 7
2018-04-27 8 NA 8
2018-04-28 9 NA 9
2018-04-29 10 NA 10
Upvotes: 1
Views: 130
Reputation: 176688
Here's another solution, and it does not use ifelse()
.
# Merge the two objects first
z <- merge(x,y)
# Create a new column from a copy of 'y'
z$z <- z$y
# Missing values in column 'z'
zNA <- is.na(z$z)
# Fill all missing values in column 'z' with values from column 'x'
z[zNA, "z"] <- z[zNA, "x"]
I personally avoid ifelse()
because the object it returns is not always intuitively predictable.
Upvotes: 2
Reputation: 363
Would that solve your problem ?
z <- rbind(x,y)
z <- z[!duplicated(z)]
Edit:
Note that rbind()
binds xts
objects by row in order of priority, i.e. the rows of y
will be before rows of x
because y
was put before x
in the function call
> rbind(y, x)
[,1]
2018-04-21 1
2018-04-22 2
2018-04-23 3
2018-04-23 5
2018-04-24 4
2018-04-24 4
2018-04-25 5
2018-04-25 5
2018-04-26 6
2018-04-26 6
2018-04-27 7
2018-04-28 8
2018-04-29 9
2018-04-30 10
Then I noticed that z[!duplicated(z)]
is not correct actually. The duplicates you want to take out are duplicates in index so try that out.
z <- rbind(y, x)
z <- z[!duplicated(index(z))]
I am a fervent user of xts
and I always try to use its functions because they usually do all the work for you in a very readable and natural fashion. But when I can't find my way out of it I often use the powerful ifelse()
, prince of efficiency and destroyer of ambiguity.
z <- merge(x, y)
zz <- ifelse(is.na(z[, 2]), z[, 1], z[, 2])
Now zz
is not an xts
object anymore so have to do
zz <- xts(zz, index(z))
But you will be left with duplicates. Since I don't know from your answer if you actually want to keep them, I'll leave you the choice.
Hope that helps :)
Upvotes: 2