R/util_raster2tibble.R

#' Converts raster data into tibble
#'
#' @description Writes spatial raster values into tibble and adds coordinates.
#'
#' @details You will loose any resolution, extent or reference system.
#' The output is raw tiles.
#'
#' @param x Raster* object
#'
#' @return a tibble
#'
#' @examples
#' maptib <- util_raster2tibble(fractal_landscape)
#' \dontrun{
#' library(ggplot2)
#' ggplot(maptib, aes(x,y)) +
#'     coord_fixed() +
#'     geom_raster(aes(fill = z))
#' }
#' @aliases util_raster2tibble
#' @rdname util_raster2tibble
#'
#' @export
#'
util_raster2tibble <- function(x) UseMethod("util_raster2tibble")

#' @name util_raster2tibble
#' @export
util_raster2tibble <- function(x) {

  # Create empty tibble with the same dimension as the raster ----
  grd <- tibble::as_tibble(expand.grid(x = seq(1, raster::ncol(x)),
                                       y = seq(raster::nrow(x), 1)))

  # Fill with raster values ----
  grd$z <- raster::values(x)

  return(grd)
}

Try the landscapetools package in your browser

Any scripts or data that you put into this service are public.

landscapetools documentation built on May 1, 2019, 9:22 p.m.