Home > Software engineering >  Using a zero-crossing algorithm with a vector
Using a zero-crossing algorithm with a vector

Time:11-24

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

CodePudding user response:

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)

CodePudding user response:

You can try the code below

transform(
  df,
  crosszero = c( (rowSums(embed(sign(x), 2)) == 0), NA)
)

which gives

   time  x crosszero
1     1  1         0
2     2  2         0
3     3  3         1
4     4 -6         0
5     5 -8         0
6     6 -2         0
7     7  0         0
8     8  1         0
9     9  2         0
10   10  3         0
11   11  4         0
12   12  2         0
13   13  1         1
14   14 -3         0
15   15 -4         0
16   16 -7         0
17   17 -4         0
18   18 -1         1
19   19  1         0
20   20  2        NA
  • Related