Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading