shany shany - 2 months ago 18
R Question

Finding element and index of an element in a vector in R

How can I find the first element and index of the element of a vector which is smaller than its previous element and it is smaller than its next element in R?

for example, we have a vector like this:

x=c(100.5, 99, 98.5,95.2,110, 116, 120,130)

I would like to find 95.2 and index of this element in R.


I think this works, but I'm happy to be proven wrong:

x <- c(100.5, 99, 98.5, 95.2, 110, 116, 120, 130)
idx <- which(diff(sign(diff(x)))==2)+1
#[1] 4
#[1] 95.2

It also doesn't consider the first value to be a possible result (not sure if this is what you want or not):

x <- 1:5
idx <- which(diff(sign(diff(x)))==2)+1