1

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.

loki
  • 9,816
  • 7
  • 56
  • 82
vineet
  • 13
  • 2
  • 1
    Please have a look at [how to write a good R Q](https://stackoverflow.com/q/5963269/3250126). Since you seem to work with large LS8 Data, please try to come up with a smaller example that shows the errors/difficulties as your large data set. – loki Aug 14 '17 at 09:49

2 Answers2

1

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)

plot with all rasters

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)
loki
  • 9,816
  • 7
  • 56
  • 82
  • i tried but the output raster does not have the minimum values. b1 is raster which has the range as mentioned values : 0, 16637 (min, max) and b2 is again a raster which has the values 0, 16961 (min, max) and when am using this min function the output rraster range an getting is 0, 24838 (min, max) – vineet Aug 14 '17 at 09:38
  • raster are the Landsat 8 bands. – vineet Aug 14 '17 at 09:43
0

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)
aldo_tapia
  • 1,153
  • 16
  • 27