Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

r - max.col with NA removal

I'm looking to find the columns of matrix row-maxima while ignoring NAs. E.g.,

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

That is:

> 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 row maxima, ignoring NAs, can be obtained using max:

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

I'm looking for the column positions of these maxima, but max.col only works for rows without any NAs.

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

How could I find the columns of (first) maximizers for the rows with some non-missing values? I.e., something like:

[1]  2  2  3  1 NA
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

We replace the 'NA' with -Inf in 'a' and apply the max.col on that.

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

But, this will return 1 for the last row which have all NAs. To return NA, we can multiply it with the NA converted negated (!) rowSums of logical matrix (!is.na(a)).

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

EDIT: Changed the replacement from 0 to -Inf based on @Frank's comment


As the OP was using apply, which.max can return the column index

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

Or

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...