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]
This is pretty simple, if you know about the sign
function...
which(diff(sign(df))!=0)
# [1] 2
I prefer Joshua's answer, but here's an alternative, more complicated one just for fun:
head(cumsum(rle(sign(df))$lengths),-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)
}
diff
function : - Tommy 2012-04-05 18:16