Skip to content
Prev 5923 / 15274 Next

Combine two incomplete zoo object (with NAs) in one zoo series

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: