#read in data set for presence/absence of two plants presabs.plants=read.table("http://www.public.iastate.edu/~pcaragea/S40608/Compute/plants.txt",header=TRUE) attach(presabs.plants) #start by defining neighbors library(spatstat)#need this to compute distances between all points in a data dist.neighbors=function(data,distance) #distance is set by user { #data has the x and y on the first two columns. Could have more than two columns, or exactly two columns, it doesn't matter. #produces a "list" object with a vector of the neighbors for each location #distance defines the range within which we define neighbors nd=length(data[,1]) nbmat=list(array) dist=pairdist(data[,1:2]) for(i in 1:nd){ nbmat[[i]]=0 for(j in 1:nd) if((dist[i,j]1]#NS ts1<-sum(ys[tnbs1]) ts2<-sum(ys[tnbs2]) Ais<-log(kappa)-log(1-kappa)+eta1*(ts1-kappa)+eta2*(ts2-kappa) if(cnt==length(ys)){break} } return(Ais) } #and the log-likelihood function: logplikdir = function(pars, ys, nbrs){ Ais=canon.dir(pars,ys,nbrs) Bis = log(1+exp(Ais)) logpliklihood = sum(ys*Ais-Bis) return(-1*logpliklihood) } Model3=optim(par=c(0.5,0.5,0.5),fn=logplikdir,ys=S68,nbrs=nb.plants,hessian=TRUE) #to get estimated parameters: Model3$par #finally, we can compute fitted values: dir.fitted = function(pars, ys, nbrs){ #produce predictions and mspe Ai = canon.dir(pars, ys, nbrs) ps = exp(Ai)/(1+exp(Ai)) mspe = mean((ys-ps)^2) list(mspe=mspe,preds=ps) } Fits.dir=dir.fitted(Model3$par,S68,nb.plants) Fits.dir$preds #returns the actual predictions at each location Fits.dir$mspe #returns the mean squared prediction errors