max.col with NA removal

后端 未结 1 2064
感动是毒
感动是毒 2020-12-19 08:42

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,] <-         


        
相关标签:
1条回答
  • 2020-12-19 09:21

    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
    
    0 讨论(0)
提交回复
热议问题