Reputation: 13
I have two raster layer of dimension (7801, 7651)
. I want to compare each pixel of one raster layer with the other and create a new raster which has the minimum pixel value
among the initial two raster. That is, if any i,j pixel
of raster 1 has value 25 and same i,j pixel
of raster 2 has value 20, thus in the output raster the i,j pixel
should be 20.
Upvotes: 1
Views: 1142
Reputation: 1228
Using @loki's example, you have three more options to calculate minimum value for both layers:
library(raster)
calc(stack(r1,r2),fun=min,na.rm=T)
stackApply(stack(r1,r2),indices = c(1,1),fun='min',na.rm=T)
overlay(r1,r2,fun=min,na.rm=T)
Upvotes: 1
Reputation: 10350
You can just use min
with two raster layers.
Let's start with a reproducible example:
library(raster)
r1 <- raster(ncol = 5, nrow = 5)
r1[] <- 1:ncell(r1)
plot(r1)
r2 <- raster(ncol = 5, nrow = 5)
r2[] <- ncell(r2):1
par(mfrow = c(1,3))
plot(r1)
plot(r2)
Now we calculate the min of each overlapping cell within the two raster layers very easily with the implemented cell statistics:
r3 <- min(r2, r1)
plot(r3)
Furthermore, you can also apply statistics like mean
, max
, etc.
If the implemented statistics somehow fail, or you want to use your own statistics, you can also directly access the data per pixel. That is, you first copy one of the raster layers.
r3 <- r1
Afterwards, you can apply a function over the values.
r3[] <- apply(cbind(r1[], r2[]), 1, min)
Upvotes: 1