7

I have a vector:

df <- c(5,9,-8,-7,-1)

How can I identify the position prior to a change in sign? ie df[2]

joran
  • 169,992
  • 32
  • 429
  • 468
adam.888
  • 7,686
  • 17
  • 70
  • 105

3 Answers3

14

This is pretty simple, if you know about the sign function...

which(diff(sign(df))!=0)
# [1] 2
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
1

I prefer Joshua's answer, but here's an alternative, more complicated one just for fun:

head(cumsum(rle(sign(df))$lengths),-1)
joran
  • 169,992
  • 32
  • 429
  • 468
  • similarly to the above answer by @JoshuaUlrich, this answer considers c(0,1) to have a sign change. This may or may not be desired depending on the application! – WetlabStudent Jun 30 '15 at 06:41
-1

If you want to be a terrible person, you could always use a for loop:

signchange <- function(x) {
    index = 0
    for(i in 1:length(x))
    {
        if(x[i] < 0)
        {
            return (index)
        }
        else
        {
            index = index + 1
        }
    }
    return (index)
}
Sandeep Dinesh
  • 2,035
  • 19
  • 19
  • 2
    I wasn't the downvote but if you're going to be a terrible person and use a loop you should at least check whether the first element is positive or negative. The function as is detects the first negative value - not the first sign change. – Dason Apr 05 '12 at 20:16