I have a bunch of ordered vectors containing numbers between 0 and 1. I need to find the index of the first element over a certain value r:
x <- c(0.1, 0.3, 0.4, 0.8)
which.max(x >= 0.4)
[1] 3 # This is exactly what I need
Now if my target value is over the maximum value in the vector, which.max() returns 1, which can be confused with the "real" first value:
which.max(x >= 0)
[1] 1
which.max(x >= 0.9) # Why?
[1] 1
How could I modify this expression to get an NA as a result?
na. rm: a logical value indicating whether NA values should be stripped before the computation proceeds. By feeding this argument a logical value ( TRUE or FALSE ) you are choosing whether to strip the NAs or not while running the function. The default (also given by the mean() documentation) is FALSE .
Max() function in R For this, we first create a vector and then apply the max() function, which returns the max value in the vector.
In R, we can find the minimum or maximum value of a vector or data frame. We use the min() and max() function to find minimum and maximum value respectively. The min() function returns the minimum value of a vector or data frame. The max() function returns the maximum value of a vector or data frame.
In R, missing values are represented by the symbol NA (not available).
Just use which()
and return the first element:
which(x > 0.3)[1]
[1] 3
which(x > 0.9)[1]
[1] NA
To understand why which.max()
doesn't work, you have to understand how R coerces your values from numeric to logical to numeric.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With