3

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.

shany
  • 175
  • 1
  • 1
  • 7
  • @thelatemail sorry I just missed some part of the question – 9Heads Dec 01 '16 at 05:39
  • check the `diff` starting from the left and right are negative `x[c(FALSE, diff(x) < 0) & rev(c(FALSE, diff(rev(x)) < 0))]` – rawr Dec 01 '16 at 06:01

2 Answers2

3

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)
thelatemail
  • 91,185
  • 12
  • 128
  • 188
2

We can try

i1 <- which(c(x[-1] > x[-length(x)] & x[-length(x)] < x[-1]), FALSE)[1]
x[i1]
#[1] 95.2
akrun
  • 874,273
  • 37
  • 540
  • 662