从Find x-intercept and y-intercept of a loop in R我得到了这个很好的解决方案。但它崩溃了,如果没有像本例中那样的拦截:
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)
}
如果没有找到拦截,我怎样才能阻止该功能崩溃并返回NA
s ?
到目前为止我尝试的是:
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)); }
}
答案 0 :(得分:5)
直接解决方案,在出现任何错误时返回NA:
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)
}