#-------------------------------------------------------------------- # Code for Article # # Spatial patterns of livestock activity on heterogeneous subalpine # pastures reveal distinct responses to environment and management # # H. Homburger, A. Lüscher, M. Scherer-Lorenzen and M.K. Schneider #--------------------------------------------------------------------- #source("http://www.math.ntnu.no/inla/givemeINLA.R") #to install INLA library(sp) library(INLA) inla.setOption("enable.inla.argument.weights", TRUE) #Needed for weighted regression #Read-in data setwd("path/to/data") grid <- read.table("exampleData.txt",sep="\t",h=T) #read dataser coordinates(grid) <- ~X+Y #SpatialPointsDataFrame gridded(grid) <- TRUE #SpatialGridDataFrame spatial data is gridded grid <- as(grid, "SpatialGridDataFrame") # convert to full grid #Visualise par(mfrow=c(3,5),mar=c(0,0,5,0)) for(i in 1:ncol(grid)) { image(grid[names(grid)[i]], col=rev(gray.colors(20))) title(main=names(grid)[i],line=1)} # Set up INLA Yvar <- "G" #Choose G, R or W n.cells <- nrow(grid) cell.area <- as.numeric(grid@grid@cellsize[1]^2) cell.dims <- grid@grid@cells.dim grid$I <- grid$J <- grid$L <- 1:n.cells grid$E <- cell.area grid$count <- grid@data[,paste("count",Yvar, sep="_")] grid$weight <- grid@data[,paste("weight",Yvar, sep="_")] grid$logdist_wat <- log(grid$dist_wat) grid$logdist_shed <- log(grid$dist_shed) stand <- function(x) (x-mean(x,na.rm=T))/sd(x,na.rm=T) # Standartization function vars <- c("Z","slope","stocking","logdist_wat","logdist_shed","insolat") grid@data[,paste(vars,"S",sep="")] <- apply(grid@data[,vars],2,stand) hyper.unst <- list(prec=list(param=c(0.5, 0.00149))) # Following Fong, Rue and Wakefield (2009), Example 5.2, and Papoila et al (2014) # Define limit for upper standard deviation alpha <- 0.001 #as in Sorbye and Rue (2012) and Papoila et al (2014) U = 0.5 a <- 1 b <- sapply(U, function(u) u^2*qgamma(alpha, shape=a,rate=1)) #Sigma^2ref is 0 since we use scale.model=T and is same for all GRMFs (see Sorbye 2013) hyper.prec <- list(prec=list(param=c(a,b))) # Define the model formula <- count ~ 1 + slopeS + veg + logdist_shedS + logdist_watS + stockingS + insolatS + f(Zs, model="rw1", scale.model=T, hyper=hyper.prec) + f(I, model="rw2d", nrow=cell.dims[1], ncol=cell.dims[2], scale.model=TRUE, hyper=hyper.prec) + #structured spatial error f(J, model="iid", hyper=hyper.unst) #Fitting the model takes about 2 mins, be patient! M <- inla(formula, data=grid@data, family="zeroinflatednbinomial0", weights=grid$weight, control.inla = list(strategy = "gaussian", int.strategy = "eb"), control.results=list(return.marginals.random=F, return.marginals.predictor=F),) summary(M) #to see the parameter estimates grid$f.spat <- M$summary.random$I$mean #Extract the spatial effect image(grid["f.spat"]) #-----------------------------------------------------------------------