The task: I'm creating a function to assess flood damage in R. The inputs are:

  • Dataframe with water depth values and corresponding damage values in percentage.
  • Raster representing water depth

The raster values must be approximated to the closest value in the first column of the df and then create a new raster with damage values using corresponding values from the second column).

damage <- cbind(c(0.0,0.2,0.4,0.6,0.8,1.0),c(0, 5, 10, 40, 70, 100))
r.wd <- raster(myraster.tif)

I've tried using which.min(abs(damage[,1]-r.wd)) but doesn't work.


Here's an option using calc.


# Create test data
r <- raster()
r[] <- rnorm(n = ncell(r), mean = 0.5, sd = 0.1)

damageDf <- data.frame(depth = c(0.0,0.2,0.4,0.6,0.8,1.0),
                       damage = c(0, 5, 10, 40, 70, 100))

# Function to be passed to calc (gets damageDf from global environment)
depth2damage <- function(x) {
    damageDf$damage[which.min(abs(damageDf$depth - x))]

# Apply function to depth raster
# You may omit forceapply = TRUE but since we know that the function
# only works for single values we might as well explicitly tell calc about it
damageRaster <- calc(r, depth2damage, forceapply = TRUE)
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.