Search code examples
rpointcurve

R: Elbow/knee points in Scatterplot


I need to identify the two elbow points in a curve with R. The curve isn't a real curve, but consists out of three linear functions. The linear functions themselfes are unknown. I've already tried different approaches, but none of them was able to identfiy the correct points. Does anyone know a solution?

enter image description here

enter image description here


Solution

  • You could look at the slope of the line and see where it changes:

    fake <- data.frame(x = c(1:9, 10*1:5, 50*2:5),
                       y = c(10:2, 0.1*10:6, 0.01*59:56))
    plot(fake)
    

    enter image description here

    # diff compares each value to the prior row. Undefined for first row so I add NA at the start
    fake$slope = c(NA, diff(fake$y)/diff(fake$x))
    fake$slope_chg = c(NA, round(diff(fake$slope),5))
    fake$change = ifelse(fake$slope_chg != 0, "change","")
    

    Result

         x     y  slope slope_chg change
    1    1 10.00     NA        NA   <NA>
    2    2  9.00 -1e+00        NA   <NA>
    3    3  8.00 -1e+00    0.0000       
    4    4  7.00 -1e+00    0.0000       
    5    5  6.00 -1e+00    0.0000       
    6    6  5.00 -1e+00    0.0000       
    7    7  4.00 -1e+00    0.0000       
    8    8  3.00 -1e+00    0.0000       
    9    9  2.00 -1e+00    0.0000       
    10  10  1.00 -1e+00    0.0000       
    11  20  0.90 -1e-02    0.9900 change
    12  30  0.80 -1e-02    0.0000       
    13  40  0.70 -1e-02    0.0000       
    14  50  0.60 -1e-02    0.0000       
    15 100  0.59 -2e-04    0.0098 change
    16 150  0.58 -2e-04    0.0000       
    17 200  0.57 -2e-04    0.0000       
    18 250  0.56 -2e-04    0.0000