rvectorna

Replace initial NA values with zero in a row until non NA column


Consider the following row in a dataset:-

#Row (initially):
NA NA NA NA NA NA NA 2 3 1 4 5 2 NA NA 6 7

I want all such rows to be transformed into

#Row  (modified) :
0  0  0  0  0  0  0 2 3 1 4 5 2 NA NA 6 7

Only the initial NA that occur before any non na value shout be replaced by zero and not those that come afterwards.

Edit: My data is matrix, example:

NA   NA   NA   NA    1    1    1    1    1     1
NA   NA   NA   NA    1    1    1    1    1     1
NA   NA   NA   NA    1    1    1    1    1     1
NA   NA   NA   NA   NA   NA   NA    1   NA     1
NA   NA   NA   NA   NA   NA   NA    1   NA     1
NA   NA   NA   NA   NA   NA   NA   NA   NA     1
1    1    1    1    1    1    1    1   NA     1
1    1    1    1    1    1    1    1    1     1

It should be modified to

0    0    0    0    1    1    1    1    1     1
0    0    0    0    1    1    1    1    1     1
0    0    0    0    1    1    1    1    1     1
0    0    0    0    0    0    0    1   NA     1
0    0    0    0    0    0    0    1   NA     1
0    0    0    0    0    0    0    0    0     1
1    1    1    1    1    1    1    1   NA     1
1    1    1    1    1    1    1    1    1     1

Solution

  • Define a function and use apply(). Here a working example. The function is just testing if the cumsum of logical values is increasing.

    x <- c(NA, NA, NA, NA, 1, 0, NA, NA, 3)
    y <- c(2, NA, 3, NA, 1, 0, NA, 2, 3)
    z <- c(NA, NA, 3, NA, 1, 0, NA, NA, 3)
    df <- data.frame(x, y, z)
    
    
    initialNA <- function(x) {
      index <- cumsum(is.na(x)) >= seq_along(x)
      x[index] <- 0
      x
    }
    
    df2 <- data.frame(t(apply(df, 1, initialNA)))