|
15 | 15 | #' @export |
16 | 16 |
|
17 | 17 | gplot_data <- function(x, maxpixels = 50000) { |
18 | | - x <- raster::sampleRegular(x, maxpixels, asRaster = TRUE) |
19 | | - coords <- raster::xyFromCell(x, seq_len(raster::ncell(x))) |
20 | | - ## Extract values |
21 | | - dat <- utils::stack(as.data.frame(raster::getValues(x))) |
22 | | - names(dat) <- c('value', 'variable') |
23 | | - # If only one variable |
24 | | - if (dat$variable[1] == "raster::getValues(x)") { |
25 | | - dat$variable <- names(x) |
26 | | - } |
27 | | - |
28 | | - dat <- dplyr::as_tibble(data.frame(coords, dat)) |
29 | | - |
30 | | - if (!is.null(levels(x))) { |
31 | | - dat <- dplyr::left_join(dat, levels(x)[[1]], |
32 | | - by = c("value" = "ID")) |
| 18 | + if (class(x) == "SpatRaster"){ # work with terra package rasters |
| 19 | + x <- terra::spatSample(x, maxpixels, as.raster = TRUE) |
| 20 | + coords <- terra::xyFromCell(x, seq_len(terra::ncell(x))) |
| 21 | + ## Extract values |
| 22 | + dat <- utils::stack(as.data.frame(terra::values(x))) |
| 23 | + names(dat) <- c('value', 'variable') |
| 24 | + # If only one variable |
| 25 | + if (dat$variable[1] == "terra::values(x)") { |
| 26 | + dat$variable <- names(x) |
| 27 | + } |
| 28 | + |
| 29 | + dat <- dplyr::as_tibble(data.frame(coords, dat)) |
| 30 | + ## OLD `gplot_data` FUNCTION |
| 31 | + }else{ # work with raster package rasters |
| 32 | + x <- raster::sampleRegular(x, maxpixels, asRaster = TRUE) |
| 33 | + coords <- raster::xyFromCell(x, seq_len(raster::ncell(x))) |
| 34 | + ## Extract values |
| 35 | + dat <- utils::stack(as.data.frame(raster::getValues(x))) |
| 36 | + names(dat) <- c('value', 'variable') |
| 37 | + # If only one variable |
| 38 | + if (dat$variable[1] == "raster::getValues(x)") { |
| 39 | + dat$variable <- names(x) |
| 40 | + } |
| 41 | + |
| 42 | + dat <- dplyr::as_tibble(data.frame(coords, dat)) |
| 43 | + |
| 44 | + if (!is.null(levels(x))) { |
| 45 | + dat <- dplyr::left_join(dat, levels(x)[[1]], |
| 46 | + by = c("value" = "ID")) |
| 47 | + } |
33 | 48 | } |
34 | 49 | dat |
35 | 50 | } |
0 commit comments