Search code examples
rmatrixmissing-datafillna

Filling missing values in R matrix using previous value in the same row


Consider the following example

before = matrix(c(1, 2, 3, NA, 4, 5, NA, NA, 1), ncol = 3)
after = matrix(c(1, 2, 3, 1, 4, 5, 1, 4, 1), ncol = 3)

The matrix before is the kind of matrix I always deal with in terms of position of missing values, whereas the matrix after is the one I need to get to repeatedly. Is there any efficient routine?


Solution

  • You can apply na.locf() from {zoo} row-wisely (MARGIN = 1L):

    > before = matrix(c(1, 2, 3, NA, 4, 5, NA, NA, 1), ncol = 3)
    > after = matrix(c(1, 2, 3, 1, 4, 5, 1, 4, 1), ncol = 3)
    > (before2 = t(apply(before, 1L, zoo::na.locf)))
         [,1] [,2] [,3]
    [1,]    1    1    1
    [2,]    2    4    4
    [3,]    3    5    1
    > identical(before2, after)
    [1] TRUE
    

    Read the documentation, there are plenty of options implemented. Or write your own function, see here.