max 在 R 中返回负无穷大

Mar*_*ler 3 r infinity

我偶然发现了一个看似简单的问题,但我无法解决。我试图在不包含兴趣值的情况下使用maxand 。理想情况下,我想获得这种情况下的号码。但我不断得到负无穷大。whichvector0

ff <- c(2, 4, 6, 8, 10)
my.index <- 1
max(which(ff == my.index))
#[1] -Inf
#Warning message:
#In max(which(ff == my.index)) :
#  no non-missing arguments to max; returning -Inf
Run Code Online (Sandbox Code Playgroud)

以下是返回相同结果的其他一些尝试:

max(as.numeric(which(ff == my.index)))
max(which(ff == my.index), na.rm = TRUE)
max(as.numeric(which(ff == my.index)), na.rm = TRUE)
max(numeric(0))
Run Code Online (Sandbox Code Playgroud)

我确实注意到:

max(0)
[1] 0
Run Code Online (Sandbox Code Playgroud)

所以,我想也许最简单的解决方案就是转换-Inf0. 还有base R比下面更优雅的解决方案吗?一条单线?理想情况下,不会返回warning消息?

aaa <- max(which(ff == my.index))
aaa[is.infinite(aaa)] <- 0
aaa
[1] 0
Run Code Online (Sandbox Code Playgroud)

the*_*ail 5

max使用传递给 的所有参数中的所有max(...)值,因此:

max(which(ff == my.index), 0)
#[1] 0
Run Code Online (Sandbox Code Playgroud)