Cocilein
Cocilein

Reputation: 45

How to use lapply over a list of rasters

I've got a raster and I need to compare the values of the first and last row. (I want to know, if there is a Cluster that connects top with bottom) That's what I've done:

V1=getValues(r,row=1)
V1=V1[V1!=0]
V1=unique(V1)

and the same with the last row. Then I do this:

V1 %in% V2

That's okay. It's working. But I need to do this with many many rasters. I thought about creating a list with these several rasters and run the script above over every raster of the list. I thought I could do that with lapply but I don't know how to do that.

Or maybe there is a possibility to get kind of a dataframe back or something like this

raster     connected 
r1         TRUE
r2         FALSE
r3         FALSE
...        ...

Upvotes: 2

Views: 1657

Answers (1)

LAP
LAP

Reputation: 6685

FUN.raster <- function(r) {
  x <- getValues(r, row = 1)
  x <- x[x!=0]
  x <- unique(x)

  y <- getValues(r, row = nrow(r))
  y <- y[y!=0]
  y <- unique(y)

  x %in% y
}

and then

sapply(rasterlist, FUN.raster)

This gives you a boolean vector of TRUE/FALSE with the length of your rasterlist.Beware that this is untested, as you didn't provide any example data.

Upvotes: 3

Related Questions