How can I find x-intercept and the y-intercept (all four) of a loop with R
?
# this will generate an example dataframe mydf
x <- sin(seq(0,2*pi,0.2) + rnorm(1))
y <- cos(seq(0,2*pi,0.2) + rnorm(1))
mydf <- data.frame(x,y)
plot(mydf)
abline(h=0)
abline(v=0)
At the moment I try around with two similar functions, that divide in north/south/east/west and look for the closest point to the axis. This is inefficient and not precise, because the point might be far away.
getYintercept <- function(mdf){
R1 <- mdf$y[which.min(subset(mdf, y>0)$y)] # north
R2 <- mdf$y[which.min(subset(mdf, y<0)$y)] # south
return(rbind(R1,R2))
}
Thus I want to interpolate (predict
, approx
) this point.
How can this be solved most elegant?
Here is an
approxfun
solution:Here,
x.s
is thex
value of the south y-intercept, and so on.