0

I would like to replace the NAs in a dataframe column with the value of the row above (or the value of the last row to have a non-NA value if there are consecutive NAs). The very first row will never be an NA.

For example I would like df to become df2

df<-expand.grid((rep ("A100",5),rep(NA,5),rep("B200",1),rep(NA,5),rep("C300",2)))

df2<-expand.grid(c(rep ("A100",10),rep("B200",6),rep("C300",2)))

I have tried a couple of for loops and ifelse statements, but can't get them to work.

There are lots of similar questions about replacing NAs with conditional statements, but I can't find something to exactly match my requirements.

Thanks.

SR_111
  • 89
  • 4
  • The `zoo` package has a function `na.locf` that will do this for you - see https://cran.r-project.org/web/packages/zoo/index.html – wjchulme Aug 22 '16 at 13:09
  • Thanks - I'll have a look. I would prefer a base R solution though it there is one. – SR_111 Aug 22 '16 at 13:10
  • 1
    Have a look at this [base R `na.locf`](http://stackoverflow.com/questions/39063253/how-to-replace-na-with-most-recent-non-na-by-group/39063544#39063544) – Steven Beaupré Aug 22 '16 at 13:11

0 Answers0