-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils_raster_io.R
53 lines (52 loc) · 1.43 KB
/
utils_raster_io.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#' Write a Raster object to disk
#'
#' Save a [terra::rast()] object to disk, along with a text file containing
#' the names of each layer in the object.
#'
#' @param x [terra::rast()] object.
#'
#' @param filename `character` file path.
#'
#' @param ... arguments passed to [raster::writeRaster()].
#'
#' @details This file saves a raster object to disk along with
#' a text file containing the layer names of the raster.
#'
#' @return None.
#'
#' @export
writeNamedRaster <- function(x, filename, ...) {
args <- list(...)
if ((!file.exists(raster::extension(filename, "txt"))) ||
isTRUE(args$overwrite)) {
writeLines(names(x), raster::extension(filename, "txt"))
}
terra::writeRaster(x, filename, ...)
}
#' Read a Raster object from disk
#'
#' Read a [raster::raster()] object from disk, along with a text file containing
#' the names of each layer in the object.
#'
#' @param x [raster::raster()] object.
#'
#' @param ... arguments passed to [raster::stack].
#'
#' @details This file reads a raster object to disk along with
#' a text file containing the layer names of the raster.
#'
#' @return A raster object.
#'
#' @export
readNamedRaster <- function(x, ...) {
assertthat::assert_that(file.exists(raster::extension(x, "txt")),
msg = "x is not a named raster"
)
n <- readLines(raster::extension(x, "txt"))
x <- suppressWarnings(raster::stack(x, ...))
names(x) <- n
if (raster::nlayers(x) == 1) {
x <- x[[1]]
}
x
}