[R-sig-Geo] comparing one raster to a stack and condition

Barry Rowlingson b.rowlingson at lancaster.ac.uk
Thu Dec 14 09:28:39 CET 2017


Here's a way - first let's make some sample data in a stack:

 maker = function(d){raster(matrix(runif(16),4,4))}
 rains = stack(lapply(1:10, maker))

so `rains` is a stack of 10 4x4 rasters with random numbers in. Now the
raster we want to test:

 r1 = maker()

Okay, all set up. We have a raster and a stack, then:

 r1 < rains

is a stack of 1s and 0s where r1 is less than the cell in each layer of
rains, and then we can do:

 sum(r1 < rains)

to total those up.

plot(sum(r1<rains))

should map how many times r1 is less than the values in rains.

Barry



On Wed, Dec 13, 2017 at 9:13 PM, karsten <karsten at terragis.net> wrote:

> Hi All,
>
> I am trying to compare one precipitation raster to a stack of precipitation
> raster and would like to create a result raster with a count of how often
> the raster value is below those of the stack.
> So far I have the following code:
>
> ----------------------------------------------
>
> library(zoo)
> library(raster)
> # create raster stack for Januaries
> alltiffs = list.files(getwd(), pattern="*\\.tif$", full.names=TRUE)
>
> #filter the ones with 01 in it for january
> januarygrids =  alltiffs[grepl("*.01.*", alltiffs)]
>
> # Create raster stack of grids
> r <- stack(januarygrids, quick=TRUE)
>
> # set current january layer to compare with
> currentmonth <- "es_af.2017.01.tif"
> currentmonthraster <- raster(currentmonth)
>
> # function to count how oftetn current ratser is below values in stack,
> input r and currentmonthraster
> belowCurrentRaster <- function(x, y) {
>   sum(x > y)
> }
>
> -------------------------------------------------------
>
> Now I thought I could use zApply or overlay to get the count from the
> belowCurrentRaster function and write those counts into a result raster.
> But I could not figure out how to make this work.
> Any ideas appreciated.
>
> Cheers
> Karsten Vennemann
> Terra GIS LTD
>
>
>         [[alternative HTML version deleted]]
>
> _______________________________________________
> R-sig-Geo mailing list
> R-sig-Geo at r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
>

	[[alternative HTML version deleted]]



More information about the R-sig-Geo mailing list