gpt4 book ai didi

r - max 在 R 中返回负无穷大

转载 作者:行者123 更新时间:2023-12-05 01:03:48 25 4
gpt4 key购买 nike

我偶然发现了一个我无法解决的看似简单的问题。我试图在不包含感兴趣值的 vector 上使用 maxwhich。理想情况下,我想在该实例中获得数字 0 。但我不断得到负无穷。

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

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

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

我确实注意到了:

max(0)
[1] 0

所以,我想也许最简单的解决方案是将 -Inf 转换为 0。有没有比下面的更优雅的 base R 解决方案?单线?理想情况下不会返回 warning 消息?

aaa <- max(which(ff == my.index))
aaa[is.infinite(aaa)] <- 0
aaa
[1] 0

最佳答案

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

max(which(ff == my.index), 0)
#[1] 0

关于r - max 在 R 中返回负无穷大,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73496269/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com