Created
June 4, 2019 18:55
-
-
Save mattbk/c5f7f7b283a9bf70ad668461006867f6 to your computer and use it in GitHub Desktop.
Collapsing a raster brick to a single categorical raster
This file contains 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) | |
library(dplyr) | |
# Brick from https://gis.stackexchange.com/a/167514/65349 | |
r1 <- raster(nrow=5, ncol=5) | |
b <- brick(setValues(r1, runif(ncell(r1))), | |
setValues(r1, runif(25 ,0.6,0.9)), | |
setValues(r1, runif(25 ,0.2,0.4)), | |
setValues(r1, runif(25 ,1,2))) | |
# Note that each layer has a different range of values | |
plot(b) | |
hist(b) | |
# Example comparing raster layers to each other | |
# (from https://gis.stackexchange.com/a/167514/65349) | |
rc <- function(x1,x2,x3,x4) { | |
case_when( x1 > x2 ~ 1, | |
x1 < x3 ~ 2, | |
TRUE ~ 0) | |
} | |
r.class <- overlay(b, fun=rc) | |
plot(r.class) | |
# Example using absolute values/thresholds/cutoffs | |
rc2 <- function(x1,x2,x3,x4) { | |
case_when( x1 < 1 & x2 > 0.65 & x3 > .30 & x4 > 1 ~ 1, # test this case first, return class 1 if true | |
x1 > 1 & x2 > 0.65 & x3 > .30 & x4 < 1 ~ 2, # test this case second, return class 2 if true | |
TRUE ~ 0) # default value if no other cases match | |
} | |
r.class2 <- overlay(b, fun=rc2) | |
plot(r.class2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment