Q:

R: find all indeces of local minima below 0

This is probably not very complicated, but I get confused by the if statements. I've got a large dataset and I'm looking for the indices of the mimima of pairs of two values below 0. Below is an example:
x <- c(-1, 2, 3, -1, -2, 1, 2, -1)

I am trying to find the indices of the values below 0 and in cases were two (or more) subsequent values are below 0, the index of the lowest value. So what I'd like to get is a vector like this
[1] 1 5 8

I've tried to solve this by looking at the derivative:
which(diff(sign(diff(test)))==2)+1

but that doesn't give me what I need, hence my failed attempt to try this with for loops and if statements
Any help is much appreciated.

A:

x <- c(-1, 2, 3, -1, -2, 1, 2, -1)
y = diff(x)
which((c(0,y)*c(-y,0)>=0) & ((c(0,y) + c(-y, 0))<0))

# [1] 1 5 8

To describe my answer:    which((c(0,y)*c(-y,0)>=0)) is finding local min and max. then combine this with second term just choose local min. 
If you are interested in values below zero you can add another conditions
which((c(0,y)*c(-y,0)>=0) & ((c(0,y) + c(-y, 0))<0) &(x<0))

If you want to select local max, you can change it to 
which((c(0,y)*c(-y,0)>=0) & ((c(0,y) + c(-y, 0))>0))
# [1] 3 7

A:

One approach with tapply:
idx <- which(x < 0)
unname(tapply(idx, c(0L, cumsum(diff(idx) > 1L)), function(i) i[which.min(x[i])]))
# 1 5 8 

