[R-SIG-Finance] Combine two incomplete zoo object (with NAs) in one zoo series
Gabor Grothendieck
ggrothendieck at gmail.com
Thu Apr 1 15:40:22 CEST 2010
ifelse returns plain vectors. Instead, try the following which
replaces the data portion of zz with the ifelse value:
# 1
zz <- z[,1]
zz[] <- ifelse(is.na(z[,1]), z[,2], z[,1])
or this one line version:
# 1a
zz <- replace(z[,1], TRUE, ifelse(is.na(z[,1]), z[,2], z[,1]))
or this:
# 2
zz <- zoo(ifelse(is.na(z[,1]), z[,2], z[,1]), time(z))
or this which avoids ifelse altogether:
# 3
zz <- z[,1]
zz[is.na(zz)] <- z[is.na(zz), 2]
or this one line version of that:
# 3a
zz <- replace(z[,1], is.na(z[,1]), z[is.na(z[,1]), 2])
or this which also avoids ifelse and uses rollapply with if ... else
... instead:
# 4
zz <- rollapply(z, 1, function(x) if (is.na(x[1])) x[2] else x[1],
by.column = FALSE)
On Thu, Apr 1, 2010 at 9:12 AM, Pierre Lapointe <pierrelap at gmail.com> wrote:
> Hello I have two times series for the same asset. Unfortunately, the series
> with the most history has been discontinued. I want to combine the old
> series with the new one in a new zoo object. I tried combining them using
> ifelse, but the result is a vector, not a zoo object. In other words, I lost
> the dates in the process.
>
> How do I get the result in a zoo object?
>
> Here's my attempt:
>
>
>
> #build series for reproducible example
>
> z <- zoo(matrix(1:20,ncol=2),
>
> as.Date(c("1992-01-10", "1992-01-17", "1992-01-24", "1992-01-31",
>
> "1992-02-07", "1992-02-14", "1992-02-21", "1992-02-28", "1992-03-06",
>
> "1992-03-13")))
>
> z[1:5,1] <-NA
>
> z[8:10,2] <-NA
>
>
>
> #initial series with imcompletes
>
> z
>
>
>
> #my function
>
> bc.combine <-function(imcomplete.1,fill.with.2){
>
> res <-ifelse(!is.na(imcomplete.1),imcomplete.1,fill.with.2)
>
> return(res)
>
> }
>
>
>
> #two zoo objects as inputs but the result is a vector
>
> bc.combine(z[,2,drop=F],z[,1,drop=F])
>
>
>
> [,1]
>
> [1,] 11
>
> [2,] 12
>
> [3,] 13
>
> [4,] 14
>
> [5,] 15
>
> [6,] 16
>
> [7,] 17
>
> [8,] 8
>
> [9,] 9
>
> [10,] 10
>
> [[alternative HTML version deleted]]
>
> _______________________________________________
> R-SIG-Finance at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-sig-finance
> -- Subscriber-posting only. If you want to post, subscribe first.
> -- Also note that this is not the r-help list where general R questions should go.
>
More information about the R-SIG-Finance
mailing list