Find x-intercept and y-intercept of a loop in R

2020-06-27 20:30发布

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)

impression of the loop

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?

标签: r
1条回答
甜甜的少女心
2楼-- · 2020-06-27 21:20

Here is an approxfun solution:

intercepts <- function(x,y) {
  x.s <- approxfun(x[y<=0], y[y<=0])(0)
  x.n <- approxfun(x[y>=0], y[y>=0])(0)
  y.w <- approxfun(y[x<=0], x[x<=0])(0)
  y.e <- approxfun(y[x>=0], x[x>=0])(0)

  list(x.s, x.n, y.w, y.e)
}

Here, x.s is the x value of the south y-intercept, and so on.

查看更多
登录 后发表回答