I have got a raster stack of 4 raster and created a single raster with each cell showing the highest value across the 4 layers as follows:
library(raster)
stack_raster <- list()
var_name <- c("tmax","tmin","drought","flood")
for(i in seq_along(var_name)){
var_ref <- var_name[i]
r <- raster(ncol=10, nrow=10)
names(r) <- var_ref
set.seed(i)
values(r) <- sample(100)
stack_raster[[i]] <- r
}
s <- raster::stack(stack_raster)
max_raster <- whiches.max(s)
plot(max_raster)
However, in the legend, instead of showing the values, I want to show the the name of actual raster that contributed to that value. How can I create such map?

