Max.col with NA Removal

I am looking to find the columns of a row-maxima matrix, ignoring NA. For instance.

set.seed(1)
a <- matrix(runif(15), ncol=3)
a[a<.3] <- NA
a[5,] <- NA

I.e:

> a
      [,1]  [,2]  [,3] 
[1,]    NA 0.898    NA 
[2,] 0.372 0.945    NA
[3,] 0.573 0.661 0.687
[4,] 0.908 0.629 0.384
[5,]    NA    NA    NA

The maximum string values, ignoring NA, can be obtained using max:

> apply(a, 1, max, na.rm=T)
[1] 0.898 0.945 0.687 0.908  -Inf

I am looking for the column positions of these highs, but max.colonly works for rows without any NA.

> max.col(a, ties.method="first")
[1] NA NA  3  1 NA

How can I find the (first) maximizer columns for rows with some missing values? Ie, something like:

[1]  2  2  3  1 NA
+3
source share
1 answer

We are replace'NA' with -Infin 'a' and apply to it max.col.

v1 <- max.col(replace(a, is.na(a), -Inf), ties.method="first")

1 , NA. NA, NA (!) rowSums (!is.na(a)).

v1 * NA^!rowSums(!is.na(a))
#[1]  2  2  3  1 NA

EDIT: replace 0 -Inf @Frank


OP apply, which.max

apply(a, 1, function(x) which.max(x)[1])
#[1]  2  2  3  1 NA

sapply(apply(a, 1, which.max), `length<-`, 1)
#[1]  2  2  3  1 NA
+3

Source: https://habr.com/ru/post/1654127/


All Articles