Search code examples
rlistrasterr-packageregion

How would I raster a list of binary matrices and find the clumps of 0s?


I have included my attempt:

set.seed(12345)
x <- matrix(sample(c(0,1), 225, prob=c(0.8,0.2), replace=TRUE), nrow = 15)

set.seed(9999)
y <- matrix(sample(c(0,1), 225, prob=c(0.8,0.2), replace=TRUE), nrow = 15)

set.seed(12345)
z <- matrix(sample(c(0,1), 225, prob=c(0.8,0.2), replace=TRUE), nrow = 15)

mat_list <- list(x, y, z)

library(igraph)
library(raster)

lapply(list, function (list) {
 Rastermat <- raster(list)
 Clumps <- as.matrix(clump(Rastermat, directions = 8))

 #turning the clumps into a list
 tot <- max(Clumps, na.rm=TRUE)
 res <- vector("list", tot)
 for (i in 1:tot){
   res[i] <- list(which(Clumps == i, arr.ind = TRUE))
 }
})

But when I run this I get an output of NULL for each matrix in the list. Can someone please help me figure out what is wrong?

Edited:

 lapply(mat_list, function (onemat) {
 Rastermat <- raster(onemat)
 Clumps <- as.matrix(clump(Rastermat, directions = 8))

 #turning the clumps into a list
 tot <- max(Clumps, na.rm=TRUE)
 res <- vector("list", tot)
 for (i in 1:tot){
   res[i] <- list(which(Clumps == i, arr.ind = TRUE))
 }
 res
})

Solution

  • I think you are struggling to understand how lapply works.

    This (from your edit):

    lapply(mat_list, function (list) {
      Rastermat <- raster(mat_list)
    

    applies the function to each element of mat_list in turn. Like calling foo(mat_list[[1]]) then foo(mat_list[[2]]) etc (where foo is like the function you've written in the lapply).

    Inside the function the element of the list is the argument to the function, which you have named list for some reason. This is a bad name for a thing in R because its the name of a function and what the function is getting is an element of the list and not a list itself.

    So then you do: Rastermat <- raster(mat_list) - which is applying raster to the whole list of rasters not the single element passed into the function as list.

    What you want is Rastermat <- raster(list) instead. Or better still, define your function as function(onemat){ and then Rastermat <- raster(onemat) to better describe what's going on.