1

I am trying to find the maximum value in each row in a matrix in r when the matrix includes NA's.

I tried to use the function rowMax() from the "qlcMatrix" package, but it doesn't handle NA's (it gives me back "NA" if the row contain at least one NA value).

Alos
  • 2,657
  • 5
  • 35
  • 47
  • Please read the info about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and how to give a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610). This will make it much easier for others to help you. – Jaap Jul 31 '16 at 13:26
  • 2
    `library(matrixStats); rowMaxs(x, na.rm = TRUE)` – Sotos Jul 31 '16 at 13:42

2 Answers2

5

Sotos' answer above works. Also check the documentation for 'apply' in base R:

apply(your_matrix, 1, max, na.rm = TRUE)
1

You can use max. If you provide the row as a vector and use max just make sure you set na.rm = TRUE.

Here is an example using a vector:

> x = c(2,4,6,10,1,5,NA)

> max(x,na.rm = TRUE)

[1] 10

Here is an example using a matrix:

> x = matrix(1:10,2,5)
> x
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    3    5    7    9
[2,]    2    4    6    8   10
> x[2,2] = NA
> x
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    3    5    7    9
[2,]    2   NA    6    8   10
> max(x[2,],na.rm = TRUE)
[1] 10

Here is a simple for loop demonstration:

for(i in 1:nrow(x)){
    y[i] = max(x[i,],na.rm = TRUE)

}
> y
[1]  9 10
Alos
  • 2,657
  • 5
  • 35
  • 47