gpt4 book ai didi

r - which.max()不返回NA

转载 作者:行者123 更新时间:2023-12-04 11:20:02 25 4
gpt4 key购买 nike

我有一堆有序向量,其中包含0到1之间的数字。我需要在某个值r上找到第一个元素的索引:

x <- c(0.1, 0.3, 0.4, 0.8)
which.max(x >= 0.4)
[1] 3 # This is exactly what I need

现在,如果我的目标值超过向量中的最大值,则which.max()返回1,即
可以与“实际”第一个值混淆:
which.max(x >= 0)
[1] 1
which.max(x >= 0.9) # Why?
[1] 1

如何修改此表达式以得到NA?

最佳答案

只需使用which()并返回第一个元素:

which(x > 0.3)[1]
[1] 3

which(x > 0.9)[1]
[1] NA

要了解 which.max()为什么不起作用,您必须了解R如何将您的值从数字强制转换为逻辑再到数字。
x > 0.9
[1] FALSE FALSE FALSE FALSE

as.numeric(x > 0.9)
[1] 0 0 0 0

max(as.numeric(x > 0.9))
[1] 0

which.max(as.numeric(x > 0.9))
[1] 1

关于r - which.max()不返回NA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17394909/

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