R/tidy_raster.R

Defines functions tidy_raster

Documented in tidy_raster

#' Coerce Raster to Tidy Data.frame
#'
#' Useful for plotting rasters with ggplot2
#'
#' Code borrowed shamelessly from the \href{https://github.com/oscarperpinan/rastervis/blob/master/R/gplot.R}{rasterVis} package.
#'
#' @param x \code{Raster*} object
#' @param n_pixels Number of cells to sample
#'
#' @return A tidy \code{tibble} of raster values
#' @export
#'
#' @examples
#'
tidy_raster <- function(x, n_pixels = 10000)  {

  x <- sampleRegular(x, n_pixels, asRaster = TRUE)

  coords <- xyFromCell(x, seq_len(ncell(x)))

  dat <- stack(as.data.frame(getValues(x)))

  names(dat) <- c('value', 'variable')

  tibble::as_tibble(cbind(coords, dat))

}
kbvernon/deseRt documentation built on May 27, 2020, 11:44 p.m.