0

I have a data that looks like this:

SN  TimeStamp      MOTOR
1   1/27/20 18:00   0
2   1/27/20 18:01   NA
3   1/27/20 18:02   1
4   1/27/20 18:03   NA
5   1/27/20 18:04   0
6   1/27/20 18:05   1
7   1/27/20 18:06   NA
8   1/27/20 18:07   NA
9   1/27/20 18:08   0

Basically, my question is how can I change the NA value to its presiding value? I mean for NA in row 2, the answer would be the same as earlier row number 1 i.e. 0. For NAs at row 7 and 8, the answer would be that of row 6 which is 1. For NA at row 4, the value would be replaced by the number in row 3, which is 1.

Is it possible to program like that?

I would be thankful if anyone could help.

Thanks.

arg0naut91
  • 14,574
  • 2
  • 17
  • 38
  • 2
    This is easily done with `zoo::na.locf` – IRTFM Feb 19 '20 at 22:59
  • 1
    This could help - https://stackoverflow.com/questions/7735647/replacing-nas-with-latest-non-na-value – arg0naut91 Feb 19 '20 at 23:00
  • Also this post can help: https://stackoverflow.com/questions/40040834/replace-na-with-previous-or-next-value-by-group-using-dplyr – dc37 Feb 19 '20 at 23:04
  • Does this answer your question? [Replace NA with previous or next value, by group, using dplyr](https://stackoverflow.com/questions/40040834/replace-na-with-previous-or-next-value-by-group-using-dplyr) – cardinal40 Feb 19 '20 at 23:04
  • This did exact opposite. That replaced NAs with the value at the bottom. Is it possible to replace the value of NA with the value exactly above it. Thanks you so much for pointing out this article. – user11570034 Feb 19 '20 at 23:07
  • `zoo::na.locf(df$MOTOR)` – Ronak Shah Feb 20 '20 at 00:44

1 Answers1

0

You could try

while(any(is.na(df$MOTOR))
{
  na_entries <- which(is.na(df$MOTOR))
  df$MOTOR[na_entries] <- df$MOTOR[na_entries - 1]
}
Allan Cameron
  • 147,086
  • 7
  • 49
  • 87