vgramfit<-function(ds,nds,evals,vgram,p0){ #function to fit variogram models using Cressie's #weighted least squares criterion # #ds is a vector of distances or displacements at which #empirical variogram values have been computed, nds gives #the number of pairs of loctions used for each value,and #evals should be a vector of those empirical variogram #values # #vgram is the name of a function giving the theoretical #variogram model -- this should take arguments of (1) parameters #needed in the variogram model, and (2) distances #or displacements (or midpoints of classes of these) as a #vector. The function vgram should return a vector of evaluated #variogram values (semi-variogram) # #p0 is a vector of starting parameter values # #define the weighted optimization function Qfnct<-function(ps,hs,nhs,ghats){ gvals<-vgram(ps,hs) crit<-sum(nhs*((ghats/gvals)-1)^2) return(crit) } #fit using the generic optimization function in R fit1<-optim(p0,Qfnct,hs=ds,nhs=nds,ghats=evals) #fit using nonlinear minimization function in R #fit2<-nlm(Qfctn,p0,hs=ds,nhs=nds,ghats=evals) res1ps<-fit1[[1]]; res1crit<-fit1[[2]] #res2ps<-fit2[[2]]; res2crit<-fit2[[1]] #res<-list(res1ps,res1crit,res2ps,res2crit) res<-list(res1ps,res1crit) return(res) }