#This script is R code for "spatial_rnd"

##This code creates a random sample of points within a polygon. It then attaches attribute data to the points.
## This is written with a loop to create 100 sets of data, which are chopped up (header and row names removed)
## and named sequentially according to an 00-99 suffix. 

#Due to the specific use of this script, there may be information generated that is superfluous in other applications.
#In this example, we are using the county of Cumbria, with 8035 farms.

##This script was generated and written 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).


library(sp)
library(maptools)
cumbria <- readShapePoly("OS_cumbria.shp") #shapefile of the county
acps <- read.table("ACPS_8035.txt") #File of attribute data for the farms
county <- read.table("cumb_county.txt") #File with a code denoting the county, for use in later simulation

#Creating 100 files
t=c(1:100)
	for (i in 1:length(t)) {
		cumb_rnd <- spsample(cumbria, 8035, type="random")
		cumrnd <- cbind(county, cumb_rnd, acps)
		suff <- sprintf("%02d",i-1)
 		write.table(cumrnd, file=sprintf("cumb_sprnd.%s.txt", suff), row.names=FALSE, col.names=FALSE)
	}