-6ren">
gpt4 book ai didi

r - 如何捕捉 "need at least two non-NA values to interpolate"

转载 作者:行者123 更新时间:2023-12-02 05:22:31 25 4
gpt4 key购买 nike

来自 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 如果找不到拦截

到目前为止我尝试的是:

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

最佳答案

直接的解决方案,在任何错误的情况下返回 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)
}

关于r - 如何捕捉 "need at least two non-NA values to interpolate",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13638682/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com