I have created a change detection plot shown in image below for two rasters having 6 classes each using the code below. Now the plot, shows the change for all the classes but i am interested in only visualizing the change for class 4 and 5 i.e. pixels where class 4/5 changed to another class or where another class changed to 4/5.
How can i do this task?
Here is my sample code:
library(raster)
library(rasterVis)
r <- raster()
set.seed(123)
lc1 <- setValues(r, sample(1:6, 64800, replace = T))
lc2 <- setValues(r, sample(1:6, 64800, replace = T))
lc1_uniq <- unique(lc1)
lc2_uniq <- unique(lc2)
grid_ <- expand.grid(lc1_uniq,lc2_uniq)
names(grid_) <- c('from','to')
grid_$code <- 1:dim(grid_)[1]
grid_$change <- grid_[,1] != grid_[,2]
head(grid_)
change <- function(x){
grid_[x[1] == grid_[,1] & x[2] == grid_[,2],'code']
}
changeDet1 <- calc(stack(lc1,lc2), fun = change)
codes_ <- data.frame(ID = grid_$code,value = paste0('from ',grid_[,1],' to ',grid_[,2]))
logical_test <- which(grid_$change == T) # remove no change classes
codes_ <- codes_[logical_test,]
# Create a Raster Attribute Table
rat <- levels(changeDet1)[[1]]
rat[["Changes"]] <- codes_
rat[["Changes"]] <- c("land","ocean/lake", "rivers","water bodies")
levels(changeDet1) <- rat
# Plot
levelplot(changeDet1, par.settings=PuOrTheme(), xlab="", ylab="")
This question continues Converting output of crosstab() in R to raster; from classified raster images to show overall land cover change in different classes?. All the details (plots,comments) might help in understanding this question more.