R/split_raster.R

Defines functions split_raster

Documented in split_raster

#' This function splits a large raster file into several smaller ones, specified by no_sides.
#' Useful if you wish to analyse a large area in parallel.
#' Run stitch_raster after your analysis to merge the pieces back together again.
#'
#' @param raster A raster object to be split.
#' @param no_sides The number of pieces per side to split a raster object. e.g no_sides = 3 will create 9 new raster files.
#' @param save Logical. If TRUE, the split raster files will be saved to your working directory.
#' @param plot Logical. If TRUE, the split files will be plotted to screen.
#' @return Returns a list of raster files.
#' @seealso stitch_raster
#' @export
#' @examples Coming soon.

split_raster <- function(raster,no_sides,save,plot,raster.name){

  h        <- ceiling(ncol(raster)/no_sides)
  v        <- ceiling(nrow(raster)/no_sides)
  agg      <- aggregate(raster,fact=c(h,v))
  agg[]    <- 1:ncell(agg)
  agg_poly <- rasterToPolygons(agg)
  names(agg_poly) <- "polis"
  r_list <- list()
  for(i in 1:ncell(agg)){
    e1          <- extent(agg_poly[agg_poly$polis==i,])
    r_list[[i]] <- crop(raster,e1)
  }
  if(save==T){
    for(i in 1:length(r_list)){
      writeRaster(r_list[[i]],filename=paste(raster.name,i,sep=""),
                  format="GTiff",datatype="INT2S",overwrite=TRUE)
    }
  }
  if(plot==T){
    par(mfrow=c(no_sides,no_sides))
    for(i in 1:length(r_list)){
      plot(r_list[[i]],axes=F,legend=F,bty="n",box=FALSE)
    }
  }
  return(r_list)
}
simon-tarr/island documentation built on May 6, 2019, 8:05 p.m.