shany - 1 year ago 136

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.

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

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)
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**