#This script is R code for “RandPtsLandcover” #This script is designed to generate 100 sets of spatially random points within a non-continuous raster # representing certain landcover types. In this example, we are looking at 3563 farms in the county of Clwyd, UK, # for which we wish to retain attributes of the number of animals for future simulations. #Due to the specific use of this script, there may be information generated that is superfluous in other applications. ##This script was generated and written in collaboration with Jim Regetz (regetz@nceas.ucsb.edu) #at the National Center for Ecological Analysis and Synthesis (NCEAS), Santa Barbara, CA. #Script annotated for publication August 10, 2012, by Sadie J. Ryan (sjryan@esf.edu). ##This function "generatePoints" takes a raster (of type SpatialPixelsDataFrame) and distributes # random points on it, using the spsample routine from R. Since the spsample function # doesn't always get the exact number of points, this function further checks the number # of points and adds 10 until the number is exceeded, then returns the first n of points. library(sp) generatePoints <- function(raster, n) { pts <- spsample(raster, n=n, type = "random") while (length(pts) < n) { pts <- rbind(pts, spsample(raster, n=10, type="random")) } return(pts[seq_len(n)]) } ## Here, we are importing the landcover ascii files (generated from ArcGIS layers) and turning them into the right kind of raster # to run through the generatePoints function library(maptools) gpclibPermit() clwyd6n <- as(readAsciiGrid("clwyd_6n.asc"), "SpatialPixelsDataFrame") #modify this for each of 24 scenarios acps <- read.table ("clwydacps.txt") #reads in the attributes of farms - modify this for each county county <- rep (56, times = 3563) #creates the county number vector - modify this for each county (aber: 66, 3086; cumbria: 8, 8035; clwyd: 56, 3563; devon: 10, 11167) t=c(1:100) for (i in 1:length(t)) { w <- generatePoints(clwyd6n, 3563) alcrnd <- cbind(county, w, acps) suff <- sprintf("%02d", i-1) write.table(alcrnd, file=sprintf("cl6n_lcrnd.%s.txt", suff), row.names=FALSE, col.names=FALSE) }