简体   繁体   中英

Inputting a function which returns a list into calc() in R

I create a logistic function, "fun", that calculates several parameters, ie: SOS, EOS, LOS, SPUDOY, and P_Tamplitude, using a .envi raster file. Ultimately, I would like to generate separate plots for each parameter.

I use calc() to perform "fun" on Data_value. It works when "fun" returns only one variable. However, calc() fails when "fun" returns all five parameters aforementioned - which is a list.

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)

After running the command above, it says there is an error. Error in setValues(out, x) : values must be numeric, integer, logical or factor

plot(equation)

Any kind of help would be appreciated. Thank you!

I tried your code with some sample data and it actually works unless I don't insert NA values. It looks like there is an issue with the number of NA values you return. The length in case that an NA occurs needs to be same as when no NA occurs. In your case it's however 1 and 5.

Try to change the following line:

return(NA)

to

return(rep(NA,5)) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM