I have a code that produces an error (see freq(x = r, zone = p)
) :
Error in `$<-.data.frame`(`*tmp*`, "zone", value = 1L) :
replacement has 1 row, data has 0
But when using tryCatch(), I'm only able to get the replacement has 1 row, data has 0
part, but I also want the Error in
$<-.data.frame(
tmp, "zone", value = 1L) :
.
# Make a raster
r <- rast(nrows=10, ncols=10)
set.seed(2)
values(r) <- sample(5, ncell(r), replace=TRUE)
freq(r)
# Make a third raster but change the extent and make it as vector
r3 <- rast(ncols=2, nrows=2)
values(r3) <- 1:ncell(r3)
ext(r3) <- ext(-25, -20, 0, 2) # almost no overlap
p <- as.polygons(r3)
# get the frequency, but see how it fails
errorkeep = tryCatch(expr = {
freq(x = r, zone = p)
},
error = function(cond) {
print(cond)
}
)
Is there a way to keep the full error message?
Just to add to this, if you return the cond
object in your error function, you could examine its structure to inform how you wish to deal with it.
library(terra)
set.seed(2)
r <- rast(nrows = 10, ncols = 10)
values(r) <- sample(5, ncell(r), replace=TRUE)
r3 <- rast(ncols = 2, nrows = 2)
values(r3) <- 1:ncell(r3)
ext(r3) <- ext(-25, -20, 0, 2)
p <- as.polygons(r3)
errorkeep <- tryCatch(
{
freq(x = r, zone = p)
},
error = function(cond) {
cond # catch the error and return the cond object
}
)
If we then examine the structure with str()
:
str(errorkeep)
#> List of 2
#> $ message: chr "replacement has 1 row, data has 0"
#> $ call : language `$<-.data.frame`(`*tmp*`, zone, value = 1L)
#> - attr(*, "class")= chr [1:3] "simpleError" "error" "condition"
We find it is really just a list containing two elements called "message" (a object of type character) and "call" (an object of type language).
Therefore, if desired you could deal with elements separately.
errorkeep$message
#> [1] "replacement has 1 row, data has 0"
errorkeep$call
#> `$<-.data.frame`(`*tmp*`, zone, value = 1L)
Created on 2025-06-05 with reprex v2.1.1