[R] replacing zeros with above/below numbers ?

arun smartpink111 at yahoo.com
Thu Feb 6 05:41:24 CET 2014


HI,
May be this helps:
a1 <-a


indx <- which(c(0,diff(a!=0)) <0)
indx1 <- which(c(0,diff(a!=0)) >0)
a[a==0] <- rep( rowMeans(cbind(a[indx-1],a[indx1])),indx1-indx)
 a
# [1] 0.97210 0.97220 0.97300 0.97230 0.97145 0.97145 0.97145 0.97060 0.96980
#[10] 0.97040 0.97100 0.96990

#Another option is na.approx() from library(zoo)
 a1[a1==0] <- NA


 na.approx(a1)  ##there is difference in the result though (depends on what you want)
 [1] 0.972100 0.972200 0.973000 0.972300 0.971875 0.971450 0.971025 0.970600
 [9] 0.969800 0.970400 0.971000 0.969900
A.K.

Dear all, 

 My data is : 

a <- c(0.9721,0.9722,0.9730,0.9723,0.0,0.0,0.0,0.9706,0.9698,0.0,0.9710,0.9699) 

I want to replace zeros with  average of before and after values
 of them.  But sometimes there is one zero sometimes more than one. What
 is the most elegant way to do this ? 
Thanks a lot 





More information about the R-help mailing list