2

From Find x-intercept and y-intercept of a loop in R I got this nice solution. But it crashes, if there is no interception of course like in this example:

x <- sin(seq(0,2*pi,0.2) + rnorm(1))
y <- cos(seq(0,2*pi,0.2) + rnorm(1))

intercepts(x,y+10)


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)
}

How can I prevent the function from crashing and return NA s if no interception could be found?

What I tried so far is:

getIntercept <- function(x,y) {

  xydf <- data.frame(x,y)
  xy.n <- subset(xydf,y>=0)
  xy.s <- subset(xydf,y<=0)
  xy.e <- subset(xydf,x>=0)
  xy.w <- subset(xydf,x<=0)

  if ((length(xy.n$y) * length(xy.s$y) >=1) & (length(xy.e$y) * length(xy.w$y) >=1)) {
   ## interception in north and south
    Ra <- approxfun(xy.n$x,xy.n$y)(0)
    Rb <- approxfun(xy.s$x, xy.s$y)(0)

   ## interception in east and west
    Ca <- approxfun(xy.e$x,xy.e$y)(0)
    Cb <- approxfun(xy.w$x,xy.w$y)(0)
    return(data.frame(Ra,Rb,Ca,Cb,
                      Rmean=mean(Ra,-Rb), Rerr=(Ra+Rb)/2,
                      Cmean=mean(Ca,-Cb), Cerr=(Ca+Cb)/2))
  } else { return(data.frame(Ra=0,Rb=0,Ca=0,Cb=0, Rmean=0, Rerr=0, Cmean=0, Cerr=0));  }
}
4

1 回答 1

5

Straightforward solution, returns NA in the case of any error:

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

  list(x.s, x.n, y.w, y.e)
}
于 2012-11-30T06:08:34.737 回答