Last active
January 22, 2024 21:20
-
-
Save jlehtoma/47b563ef1c164c50452200a316567168 to your computer and use it in GitHub Desktop.
Count non-zero raster cells in R
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(raster) | |
# Määritä tulostiedosto | |
results_csv <- "original_areas.csv" | |
# Aseta työkansio | |
setwd("[TYÖKANSIO]") | |
# Listaa kaikki tif-tiedostot kansiossa | |
feature_files <- list.files(pattern = "*.tif$") | |
# Apufunktio solulukumäärien laskemiseen | |
get_cell_count <- function(x) { | |
message("Processing feature: ", x) | |
# Poista puuttuvat arvot (NA) | |
feature_values <- na.omit(getValues(raster(x))) | |
# Jätä nollat (0) huomiotta | |
return(sum(feature_values > 0)) | |
} | |
# Laske solulukumäärät | |
cell_counts <- sapply(feature_files, get_cell_count) | |
# Luo tulostietorakenne | |
cell_counts_df <- data.frame(feature = names(cell_counts), count = cell_counts, | |
row.names = 1:length(cell_counts)) | |
# Tallenna | |
write.csv(cell_counts_df, results_csv, row.names = FALSE) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment