[R] with replace na with 0?

Rolf Turner r@turner @end|ng |rom @uck|@nd@@c@nz
Sat Jun 12 01:16:29 CEST 2021

On Fri, 11 Jun 2021 16:15:06 +0200
Enrico Gabrielli <enricogabrielli76.peragr using gmail.com> wrote:

> Hello
> I almost got through the problem in post "aggregation of irregular
> interval time-series"
> I just don't understand how to fix that when I try
> ''
> with(datatable,ifelse(is.na(x),y,x))
> ''
> if y is na
> replaces me with 0
> and not with na
> Thank you

Works fine for me.  There's something going on that you're not
telling us or have messed up.


x <- 1:10
x[c(1,3,5)] <- NA
y <- (1:10)/10
y[c(3,5,7)] <- NA
mung <- data.frame(x=x,y=y)
gorp <- with(mung,ifelse(is.na(x),y,x))

No spurious zeroes.

Note however that this is yet another example of the unnecessary use of
ifelse().  Much better is:

gorp2 <- x
i <- is.na(x)
gorp2[i] <- y[i]


all.equal(gorp,gorp2) # TRUE

As has been pointed out, you should include a minimal reproducible
example in questions such as this.  Creating such an example almost
always reveals the source of the problem so that you can solve it


Rolf Turner

Honorary Research Fellow
Department of Statistics
University of Auckland
Phone: +64-9-373-7599 ext. 88276

More information about the R-help mailing list