# Run only if GRASS installation is found and 'terra' package is installed
GRASS_INSTALLATION <- Sys.getenv("GRASS_INSTALLATION")
run <- nzchar(GRASS_INSTALLATION) &&
file.exists(GRASS_INSTALLATION) &&
file.info(GRASS_INSTALLATION)$isdir &&
require(terra, quietly = TRUE)
if (run) {
# Get the terra example dataset
f <- system.file("ex/elev.tif", package="terra")
r <- rast(f)
}
# Check for existing GRASS session running
if (run) {
loc_existing <- try(gmeta(), silent = TRUE)
}
if (run) {
# Initialize a temporary GRASS project using the example data
loc <- initGRASS(
gisBase = GRASS_INSTALLATION,
home = tempdir(),
SG = r,
override = TRUE
)
}
if (run) {
# Write the example data to the GRASS database
write_RAST(r, "elev", flags = "overwrite")
execGRASS("r.info", map = "elev")
}
if (run) {
# Calculate slope and aspect raster
execGRASS(
"r.slope.aspect",
flags = "overwrite",
elevation = "elev",
slope = "slope",
aspect = "aspect"
)
}
if (run) {
# Read the results back into R and plot
u1 <- read_RAST(c("elev", "slope", "aspect"), return_format = "terra")
plot(u1[["elev"]], col = terrain.colors(50))
}
# Restore the original GRASS session
if (run) {
if (!inherits(loc_existing, "try-error")) {
loc <- initGRASS(
home = tempdir(),
gisBase = GRASS_INSTALLATION,
gisDbase = loc_existing$GISDBASE,
location = loc_existing$LOCATION_NAME,
mapset = loc_existing$MAPSET,
override = TRUE
)
}
}
Run the code above in your browser using DataLab