去除NA的最大col [英] max.col with NA removal

查看:85
本文介绍了去除NA的最大col的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找矩阵行最大值的列,而忽略了NA.例如,

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

也就是说:

> 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

可以使用max获得忽略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

我正在寻找这些最大值的列位置,但是max.col仅适用于没有任何NA的行.

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

推荐答案

我们将replace'NA'与中的-Inf并在其上应用max.col.

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")

但是,这将为具有所有NA的最后一行返回1.要返回NA,我们可以将其乘以逻辑矩阵(!is.na(a))的NA转换后的负数(!)rowSums.

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

基于@Frank的注释,将replace项从0更改为-Inf

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

当OP使用apply时,which.max可以返回列索引

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

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

这篇关于去除NA的最大col的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆