I have some problems with a zero crossing algorithm. Lets suppose we have this dataset:
time <- c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20)
x <- c(1,2,3,-2 -4,-8,-2,0,1,2,3,4,2,1,-3,-4,-7,-4,-1,1,2)
df <- data.frame(time, x)
df
I need to write a function in R creating a new column in df indicating when X passes from positive to negative:
0 indicates no zero crossing, 1 a zero crossing.
It should be easy to do, but so far I haven't found a solution.
Got any advice for me?
Best regards
Find rows where sign is negative (first condition) and positive on position before (second condition):
df$pass <- ifelse(sign(df$x) < 0 & lag(sign(df$x)) >= 0, 1, 0)