shany - 3 months ago 22

R Question

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.

Answer

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
idx
#[1] 4
x[idx]
#[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
idx
#numeric(0)
```