简体   繁体   中英

How can I detect changes from negative to positive value?

I have calculated the differences of my data points and received this vector:

> diff(smooth$a)/(diff(smooth$b))
 [1] -0.0099976150  0.0011162606  0.0116275973  0.0247594149  0.0213592319  0.0205187495  0.0179274056  0.0207752713
 [9]  0.0231903072 -0.0077549224 -0.0401528643 -0.0477294350 -0.0340842051 -0.0148157337  0.0003829642  0.0160912230
[17]  0.0311189830

Now I want to get the positions (index) where I have a change from negative to positive when the following 3 data points are also positive.

So my output would be like this:

> output 
 -0.0099976150 -0.0148157337

How could I do this?

One way like this:

series <- paste(ifelse(vec < 0, 0, 1), collapse = '')

vec[gregexpr('0111', series)[[1]]]
#[1] -0.009997615 -0.014815734

The first line creates a sequence of 0s and 1s depending on the sign of the number. In the second line of the code we capture the sequence with gregexpr . Finally, we use these indices to subset the original vector.

Imagine a vector z:

z <- seq(-2, 2, length.out = 20)
z
#> [1] -2.0000000 -1.7894737 -1.5789474 -1.3684211 -1.1578947 -0.9473684 -0.7368421 -0.5263158
#> [9] -0.3157895 -0.1052632  0.1052632  0.3157895  0.5263158  0.7368421  0.9473684  1.1578947
#> [17] 1.3684211  1.5789474  1.7894737  2.0000000

then you can do

turn_point <- which(z == max(z[z < 0]))
turn_plus_one <- c(turn_point, turn_point + 1)
z[turn_plus_one]
#> [1] -0.1052632  0.1052632

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM