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
  • 163,977
  • 32
  • 423
  • 453
adam.888
  • 7,336
  • 17
  • 63
  • 102

3 Answers3

14

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

which(diff(sign(df))!=0)
# [1] 2
Joshua Ulrich
  • 168,168
  • 29
  • 327
  • 408
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
  • 163,977
  • 32
  • 423
  • 453
  • 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
  • 1,905
  • 16
  • 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