I have spatraster stack, how can I update the max value for each layer?

33 Views Asked by At

I have spatraster stack, how can I update the max value for each layer with a value from a seperate dataframe? The names of rasters match the column names in the dataframe.

I'm very new to R and terra, but so far I have tried writing a for loop but my computer crashes.

Here is my code

for (i in 1:nlyr(rast)) {
  layer_values <- winter_rastI[[i]]
  layer_values[layer_values == 1] <- maxvalues[i]
  rast[[i]] <- layer_values
}
1

There are 1 best solutions below

0
Robert Hijmans On

Example data

library(terra)
s <- rast(system.file("ex/logo.tif", package="terra"))  / 1:3 
newvals <- c(800, 500, 200)

Get the max values

# efficient if the max is already available
mx <- minmax(s, compute=TRUE)[2,]
# alternative 
#mx <- global(s, max)[,1]

Use a loop

r <- s
for (i in 1:nlyr(r)) {
    r[[i]] <- subst(r[[i]], mx[i], newvals[i])
}
r

or lapply

r <- lapply(1:nlyr(s), \(i) subst(s[[i]], mx[i], newvals[i]))
r <- rast(r)