Skip to content

Commit 921ca46

Browse files
committed
memory-safer
1 parent 5bfc25a commit 921ca46

File tree

1 file changed

+15
-4
lines changed

1 file changed

+15
-4
lines changed

R/layers.R

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -325,11 +325,15 @@ addRasterImage <- function(
325325
addRasterLegend <- function(map, x, layer = 1, ...) {
326326
stopifnot(inherits(x, "SpatRaster"))
327327
stopifnot(length(layer) == 1 && layer > 0 && layer <= terra::nlyr(x))
328-
328+
329+
## might as well do this here and only once. Subsetting would otherwise have been necessary in
330+
## color_info <- base::subset(color_info, value %in% terra::values(x))
331+
x <- x[[layer]]
332+
329333
# Retrieve the color table from the layer. If one doesn't exist, that means
330334
# the raster was colored some other way, like using colorFactor or something,
331335
# and the regular addLegend() is designed for those cases.
332-
ct <- terra::coltab(x)[[layer]]
336+
ct <- terra::coltab(x)[[1]]
333337
if (is.null(ct)) {
334338
stop("addRasterLegend() can only be used on layers with color tables (see ?terra::coltab). Otherwise, use addLegend().")
335339
}
@@ -341,10 +345,17 @@ addRasterLegend <- function(map, x, layer = 1, ...) {
341345
color = grDevices::rgb(ct$red/255, ct$green/255, ct$blue/255, ct$alpha/255)
342346
)
343347

348+
lvls <- terra::levels(x)[[1]]
349+
344350
# Drop values that aren't part of the layer
345-
color_info <- base::subset(color_info, value %in% terra::values(x))
351+
## unlike "values", "unique" is memory-safe; it does not load all values
352+
## into memory if the raster is large. So instead of:
353+
354+
# color_info <- base::subset(color_info, value %in% terra::values(x))
346355

347-
lvls <- terra::levels(x)[[layer]]
356+
## remove the levels to get the raw cell values
357+
levels(x) <- NULL
358+
color_info <- base::subset(color_info, value %in% terra::unique(x)[[1]])
348359

349360
res <- if (is.data.frame(lvls)) {
350361
# Use the labels from levels(x), and look up the matching colors in the

0 commit comments

Comments
 (0)