Skip to content

Commit 9d58543

Browse files
authored
Handle SpatRaster class rasters
Handle SpatRaster class rasters from terra package.
1 parent 4e88026 commit 9d58543

File tree

1 file changed

+30
-15
lines changed

1 file changed

+30
-15
lines changed

R/gplot_data.R

Lines changed: 30 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -15,21 +15,36 @@
1515
#' @export
1616

1717
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+
}
3348
}
3449
dat
3550
}

0 commit comments

Comments
 (0)