R identifying a row prior to a change in sign

Go To StackoverFlow.com

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]

2012-04-05 18:07
by adam.888


14

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

which(diff(sign(df))!=0)
# [1] 2
2012-04-05 18:14
by Joshua Ulrich
...and if you know about the diff function : - Tommy 2012-04-05 18:16
Thank you. That's very helpful - adam.888 2012-04-07 08:49
Be careful, this answer considers c(0,1) to have a sign change. This may or may not be desired depending on the application - WetlabStudent 2015-06-30 06:39


1

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

head(cumsum(rle(sign(df))$lengths),-1)
2012-04-05 18:16
by joran
+1 for complicated fun - Joshua Ulrich 2012-04-05 18:22
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 2015-06-30 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)
}
2012-04-05 18:20
by Sandeep Dinesh
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 2012-04-05 20:16
Ads