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

57 Views Asked by At

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?

3

There are 3 best solutions below

0
Friede On BEST ANSWER

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.

0
rosapluesch On

You can do it like this:

before[is.na(before)] <- before[which(is.na(before))-nrow(before)]

In case you have more than one NA per row, you may use a loop:

while(any(is.na(before))){
  before[is.na(before)] <- before[which(is.na(before))-nrow(before)]
}

> identical(before,after)
[1] TRUE
0
jay.sf On

We can replace with tail of length 1 of the non-NAs.

> t(apply(before, 1, \(x) replace(x, is.na(x), tail(x[!is.na(x)], 1))))
     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    2    4    4
[3,]    3    5    1