在 R 中将 returns 列表的函数输入到 calc() 中
Inputting a function which returns a list into calc() in R
我创建了一个逻辑函数 "fun",它使用 .envi 栅格文件计算几个参数,即:SOS、EOS、LOS、SPUDOY 和 P_Tamplitude。最终,我想为每个参数生成单独的图。
我使用 calc() 在 Data_value 上执行 "fun"。当 "fun" returns 只有一个变量时有效。但是,当 "fun" returns 上述所有五个参数时, calc() 失败 - 这是一个列表。
new <- stack("1982_test.envi")
new[new<=-1000]<-0
Data_value<-new/10000
DOY<-(1:nlayers(new)*15)
fun<- function(x) { if (all(is.na(x[1]))) { return (NA) } else {
fitForThisData <-nls(x~ a+((b/(1+ exp(-c*(DOY-e))))- (g/(1+ exp(-d*(DOY-
f))))), alg="port",start=list(a=0.1,b=1,g=1,c=0.04,d=0.04,e=112,f=218),
lower=list(a=0,b=0.3,g=0.3,c=-1,d=-1,e=20,f=100),
upper=list(a=0.4,b=2,g=2,c=1,d=1,e=230,f=365),
control=nls.control(maxiter=2000, tol = 1e-15, minFactor = 1/1024,
warnOnly=TRUE))
SOS<-(coef(fitForThisData)[6] -(4.562/(2*coef(fitForThisData)[4])))
EOS<-(coef(fitForThisData)[7] -(4.562/(2*coef(fitForThisData)[5])))
LOS<-(EOS-SOS)
SPUDOY<-(1.317*((-1/coef(fitForThisData)[4])+ coef(fitForThisData)[6]))
P_TAmplitude<-(SPUDOY-SOS)
return (c(SOS,EOS,LOS,SPUDOY,P_TAmplitude))
}
}
equation<-calc(Data_value,fun)
在运行上面的命令之后,它说有一个错误。
setValues(out, x) 错误:
值必须是数字、整数、逻辑值或因子
plot(equation)
如有任何帮助,我们将不胜感激。谢谢!
我用一些示例数据尝试了您的代码,它确实有效,除非我不插入 NA 值。
看起来你 return 的 NA 值数量有问题。
出现 NA 时的长度需要与不出现 NA 时的长度相同。在您的情况下,它是 1 和 5。
尝试更改以下行:
return(NA)
至
return(rep(NA,5))
我创建了一个逻辑函数 "fun",它使用 .envi 栅格文件计算几个参数,即:SOS、EOS、LOS、SPUDOY 和 P_Tamplitude。最终,我想为每个参数生成单独的图。
我使用 calc() 在 Data_value 上执行 "fun"。当 "fun" returns 只有一个变量时有效。但是,当 "fun" returns 上述所有五个参数时, calc() 失败 - 这是一个列表。
new <- stack("1982_test.envi")
new[new<=-1000]<-0
Data_value<-new/10000
DOY<-(1:nlayers(new)*15)
fun<- function(x) { if (all(is.na(x[1]))) { return (NA) } else {
fitForThisData <-nls(x~ a+((b/(1+ exp(-c*(DOY-e))))- (g/(1+ exp(-d*(DOY-
f))))), alg="port",start=list(a=0.1,b=1,g=1,c=0.04,d=0.04,e=112,f=218),
lower=list(a=0,b=0.3,g=0.3,c=-1,d=-1,e=20,f=100),
upper=list(a=0.4,b=2,g=2,c=1,d=1,e=230,f=365),
control=nls.control(maxiter=2000, tol = 1e-15, minFactor = 1/1024,
warnOnly=TRUE))
SOS<-(coef(fitForThisData)[6] -(4.562/(2*coef(fitForThisData)[4])))
EOS<-(coef(fitForThisData)[7] -(4.562/(2*coef(fitForThisData)[5])))
LOS<-(EOS-SOS)
SPUDOY<-(1.317*((-1/coef(fitForThisData)[4])+ coef(fitForThisData)[6]))
P_TAmplitude<-(SPUDOY-SOS)
return (c(SOS,EOS,LOS,SPUDOY,P_TAmplitude))
}
}
equation<-calc(Data_value,fun)
在运行上面的命令之后,它说有一个错误。 setValues(out, x) 错误: 值必须是数字、整数、逻辑值或因子
plot(equation)
如有任何帮助,我们将不胜感激。谢谢!
我用一些示例数据尝试了您的代码,它确实有效,除非我不插入 NA 值。 看起来你 return 的 NA 值数量有问题。 出现 NA 时的长度需要与不出现 NA 时的长度相同。在您的情况下,它是 1 和 5。
尝试更改以下行:
return(NA)
至
return(rep(NA,5))