我将如何栅格化二进制矩阵列表并找到 0 的块?

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

我已经包含了我的尝试:

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))
 }
})

但是当我 运行 这样做时,我得到列表中每个矩阵的 NULL 输出。有人可以帮我找出问题所在吗?

已编辑:

 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
})

我认为您很难理解 lapply 的工作原理。

这个(来自您的编辑):

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

依次将函数应用于 mat_list 的每个元素。就像调用 foo(mat_list[[1]]) 然后 foo(mat_list[[2]]) 等(其中 foo 就像您在 lapply 中编写的函数)。

在函数内部,列表的元素是函数的参数,您出于某种原因将其命名为 list。对于 R 中的事物来说,这是一个糟糕的名称,因为它是一个函数的名称,而该函数得到的是列表的一个元素,而不是列表本身。

然后你做:Rastermat <- raster(mat_list) - 将 raster 应用于 整个栅格列表 而不是作为 [ 传递给函数的单个元素=17=].

您想要的是 Rastermat <- raster(list)。或者更好的是,将您的函数定义为 function(onemat){ 然后 Rastermat <- raster(onemat) 以更好地描述正在发生的事情。