R/sampleDist.R

Defines functions sampleDist

Documented in sampleDist

#' Sample data according to a spatial sampling window.
#'
#' @param data Data.frame. (colnames:x,y). A dataframe of species occurrences (x,y).
#' @param window Data.frame. (colnames:x,y). A dataframe of the sampling window/occurrences (x,y).
#' @param id Vector. A vector of sampling IDs (e.g. collection numbers)
#' @param res Numeric. Value used to convert sampling points into a sampling grid. The value of res indicates the resolution of the raster generated. A higher value generates more generous sampling, while lower represents more conservative sampling. If used in conjunction with LBGSim(), res should equal the same as used by LBGtype().
#' @return A data.frame of the original input data and whether the data would be sampled or not.  
#' @importFrom sp SpatialPointsDataFrame
#' @importFrom raster rasterize raster extract
#' @export
sampleDist <- function(data, window, id, res, method, write = FALSE, name = "simulation"){
  dat <- data
  occ <- sp::SpatialPointsDataFrame(coords = cbind.data.frame(data$x, data$y), data = data)
  x <- window$x
  y <- window$y
  z <- id
  xyz <- cbind.data.frame(x, y, z)
  xyz <- sp::SpatialPointsDataFrame(coords = cbind.data.frame(xyz$x, xyz$y), data = xyz)
  r <- raster::raster(res = res)
  ras <- raster::rasterize(xyz, r, 'z', function(x, ...) length(unique(na.omit(x))))
  dat <- cbind.data.frame(dat,raster::extract(ras, occ, cellnumbers = TRUE, df = TRUE, method = "simple", na.rm = TRUE))
  names(dat)[names(dat) == "layer"] <- "collections"
  dat$collections[is.na(dat$collections)] <- 0
  dat <- subset(dat, !collections == 0) #subset data to those sampled
  if(write == TRUE){
    suppressWarnings(dir.create("./Sampled/"))
    write.csv(dat, paste("./Sampled/", name, "_sampled.csv", sep =""), row.names = FALSE)
  }
  return(dat)
}
LewisAJones/LBGSim documentation built on March 28, 2020, 12:03 a.m.