[英]How to catch “need at least two non-NA values to interpolate”
From Find x-intercept and y-intercept of a loop in R I got this nice solution. 从R中查找循环的x截距和y截距,我得到了一个不错的解决方案。 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 ? 如果找不到拦截,如何防止函数崩溃并返回
NA
?
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)); }
}
Straightforward solution, returns NA in the case of any error: 简单的解决方案,如果出现任何错误,则返回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)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.