I have a vector x
:
x <- c(-1,-0.5,-0.1,-0.001,0.5,0.6,0.9)
I want the index of the closest negative value to zero and the closest positive value to zero. In this case, 4 and 5. x
is not necessarily sorted.
I can do this by setting numbers to NA:
# negative numbers only
tmp <- x
tmp[x > 0] <- NA
which.max(tmp)
# positive numbers only
tmp <- x
tmp[x < 0] <- NA
which.min(tmp)
But that seems clunky. Any tips?