Search code examples
rintersectionspline

Check how many times smooth spline intersects with x-axis


I want to check how many times my smoothed spline intersects with the x-axis. Is there an elegant way to do this?

Example: (1 intersection in this case)

Text](https://stackoverflow.com/[![image.jpg]1)


Solution

  • Check the number of times y values go from positive to negative

    set.seed(1571933401)
    x = 1:100
    y = rnorm(100)
    sp = smooth.spline(x, y)
    
    with(sp, sum((sign(c(0, y)) * sign(c(y, 0))) == -1))
    #6
    
    graphics.off()
    plot(sp, type = "l")
    abline(h = 0, lty = 2)
    

    enter image description here