I would like to print some details to screen/file for error checking with custom extract function. Note that this is for large raster files.
Goal
- Print the polygon
IDto screen so I can see the progress - Write the function output to a .csv file so I can check values
Attempt
# Setup
x1 <- r
vals <- sample(10, ncell(r), replace = TRUE, prob = NULL)
x <- sort(sample(ncell(r), 200))
x <- c(x, x + 1)
vals[x] <- NA
values(x1) <- vals
x1 <- ifelse(is.na(r), NA, x1)
names(x1) <- "testvals"
rr <- c(r, x1)
vls <- 1:ncell(r)
of <- "tmp.csv"
if (file.exists(of)) {
file.remove(of)
}
out <- terra::extract(rr, v, ID = TRUE, fun = function(x) {
sums <- sum(x, na.rm = TRUE)
pxlscount <- length(!is.na(x))
print(paste0("doing value: ", x))
# print(paste0("doing polygon: ", ID)) # I want to show the ID of v
# out <- bind_cols(ID, sums, pxlscount) # would like to add an ID column to out, and manipulate the names of the columns
out <- cbind(sums, pxlscount)
if (!file.exists(of)) {
cat(out, file = of, append = FALSE, sep = ",")
}
if (file.exists(of)) {
cat(out, file = of, append = TRUE, sep = ",")
}
return(out)
})