In R create maximum raster from mulitple raster files

90 views Asked by At

I am kind of new R so maybe its a stupid question but i cant figure it out myself.

This is my problem. I have multiple asc files with the same gridsize and cover the same area. I want to get the maximum value for each grid from all the asc files. I tried multiple things:

   for (i in 1:144){
    asc0<-rasterToPoints(raster(asc0))
        asc1<-rasterToPoints(raster(asc[i]))
        asc0[,3] <-pmax(asc0[,3], asc1[,3])
    }

This one fails when I loop threw the files, becasue it leaves out the NA, so my asc0 (my base file) is a different size than my next file asc1[2].

Does anyone know a way to this? I have my loops ready to go through all the files, there are 13x144 files. But I cant figure out a way to get the maximum value, store it, and compare it to the next file.

Thanks, really appriciate your help!!!

1

There are 1 answers

0
AudioBubble On BEST ANSWER

Use stack and max:

r1 <- r2 <- r3 <- raster(nrows=10, ncols=10, xmn=0, xmx=10, ymn=0, ymx=10)
r1[] <- 1   # raster with 1
r2[] <- 2   # raster with 2
r3[] <- 3   # raster with 3
s1 <- stack(r1, r2, r3)
s1
#class       : RasterStack 
#dimensions  : 10, 10, 100, 3  (nrow, ncol, ncell, nlayers)
#resolution  : 1, 1  (x, y)
#extent      : 0, 10, 0, 10  (xmin, xmax, ymin, ymax)
#coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0 
#names       : layer.1, layer.2, layer.3 
#min values  :       1,       2,       3    <- values between 1 and 3
#max values  :       1,       2,       3    <- values between 1 and 3

max(s1)
#class       : RasterLayer 
#dimensions  : 10, 10, 100  (nrow, ncol, ncell)
#resolution  : 1, 1  (x, y)
#extent      : 0, 10, 0, 10  (xmin, xmax, ymin, ymax)
#coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0 
#data source : in memory
#names       : layer 
#values      : 3, 3  (min, max)   <- 3 only