Moves all of the NA values in the rows or columns of a matrix to the end of the respective rows or columns.

naLast(inmat, by = "row", outList = FALSE, fill = NA)

Arguments

inmat

The input matrix.

by

Should be either "row" or "col", depending on if you want to shift non-NA values left or up.

outList

Logical. Do you just want a list of the non-NA values? Defaults to FALSE.

fill

While you're at it, do you want to replace NA with some other value?

Value

Either a matrix with the same dimensions as the input matrix or a list with the same number of rows or columns as the input matrix (depending on the choice made in by).

References

http://stackoverflow.com/q/23008142/1270695

Author

Ananda Mahto

Examples

set.seed(1) m <- matrix(sample(25, 20, TRUE), ncol = 4, dimnames = list(letters[1:5], LETTERS[1:4])) m[sample(prod(dim(m)), prod(dim(m)) * .6)] <- NA m
#> A B C D #> a NA 23 1 14 #> b NA 11 NA NA #> c NA 14 21 7 #> d NA NA NA NA #> e NA NA 22 NA
naLast(m, by = "row")
#> A B C D #> a 23 1 14 NA #> b 11 NA NA NA #> c 14 21 7 NA #> d NA NA NA NA #> e 22 NA NA NA
naLast(m, by = "col")
#> A B C D #> a NA 23 1 14 #> b NA 11 21 7 #> c NA 14 22 NA #> d NA NA NA NA #> e NA NA NA NA
naLast(m, by = "col", outList = TRUE)
#> [[1]] #> named integer(0) #> #> [[2]] #> a b c #> 23 11 14 #> #> [[3]] #> a c e #> 1 21 22 #> #> [[4]] #> a c #> 14 7 #>