Search code examples
rdataframeintersectionerrorbar

Finding points of intersection between error bars and a line


I have a data frame with raw data split into 2 columns corresponding to the x and y-axis. I added error bars through arrows() function (only vertical ones) based on standard deviation, and I also used abline() function to plot a 45° line.

df1 <- data.frame(col1= c(5.37, 2.86, 2.72, 4.62, 5.76, 3.07, 1.35, 6.12),
                  col2= c(4.06, 4.50, 3.90, 5.62, 4.65, 6.18, -0.31, 8.42))

plot(df1$col1, df1$col2,
     xlab="x",
     ylab="y",
     pch=19,
     xlim=c(-2,10),
     ylim=c(-2,10),
     col="blue")

abline(0,1,lty=1,lwd=2,col="black") # 45° line

df1_sd <- apply(df1, 2, sd)

# Adding vertical arrows (error bars)
arrows(x0=df1$col1, y0=(df1$col2-df1_sd[[1]]), 
       x1=df1$col1, y1=(df1$col2+df1_sd[[1]]), 
       code=3, col="blue", angle=90, length=0.1)

I aim to select the points (from the data frame) which are intersecting the 45° line, taking into account the error bar.

As an exemplification, I would like to remove the two points marked in yellow from my output (since they're out of my tolerance).

enter image description here

Can you please guide me on how to achieve this?


Solution

  • subset(df1, col1 >col2 - df1_sd[1] & col1< col2 + df1_sd[2])
      col1  col2
    1 5.37  4.06
    2 2.86  4.50
    3 2.72  3.90
    4 4.62  5.62
    5 5.76  4.65
    7 1.35 -0.31
    

    Note that the 6th and 8th points have been removed

    enter image description here