Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

which.max() does not return NA

Tags:

r

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?

like image 835
ap53 Avatar asked Jun 30 '13 21:06

ap53


People also ask

What does na RM true do in Max () and mean () functions?

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 .

How do I return a max value in R?

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.

What is max function in R?

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.

Is Na code in R?

In R, missing values are represented by the symbol NA (not available).


1 Answers

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
like image 162
Andrie Avatar answered Sep 30 '22 21:09

Andrie