我如何在列表中的多个二进制数据帧中找到 0 组的计数?

How would I find the count of groups of 0s in multiple binary data frames in a list?

我正在尝试输出列表中多个数据帧中 0 上的组数。我相信我需要执行此操作的包是光栅 R 包。这是我的尝试...

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

set.seed(99999)
output_2 <- matrix(sample(c(0,1), 225, prob=c(0.8,0.2), replace=TRUE), nrow = 15)
df_output_2 <- data.frame(output_2)

output_list <- list(df_output_2, df_output_2)

install.packages("raster")
library(raster)

lapply(output_list, function (onedf) {
  Rastermat <- raster(onedf)
  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
})

但我收到以下错误:

Error in .local(x, ...) : list has no "x"

  1. stop("list has no \"x\"")

  2. .local(x, ...)

  3. raster(onedf)

  4. raster(onedf)

  5. FUN(X[[i]], ...)

1.lapply(df_list, function(onedf) {

Rastermat <- raster(onedf)

Clumps <- as.matrix(clump(Rastermat, directions = 8))

tot <- max(Clumps, na.rm = TRUE) ...

有人可以帮助我吗?我真的不知道该怎么做。

唯一的问题是您需要使用矩阵而不是 data.frames。

这应该有效:

library(raster)
set.seed(12345)
output_1 <- matrix(sample(c(0,1), 225, prob=c(0.8,0.2), replace=TRUE), nrow = 15)
set.seed(99999)
output_2 <- matrix(sample(c(0,1), 225, prob=c(0.8,0.2), replace=TRUE), nrow = 15)

output_list <- list(output_2, output_2)

lapply(output_list, function (onedf) {
  Rastermat <- raster(onedf)
  Clumps <- as.matrix(clump(Rastermat, directions = 8))
  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
})

编辑以回答您的后续问题:

前提是您的输入data.frames包含 0 和 1,并且您想要计算 0 的簇数可以使用以下代码 return 每个 data.frame:

中的团块数量列表
sapply(list_of_dfs, function(df) {
  rm <- raster(as.matrix(df)-1) # -1 because the clump function counts non-zero values
  rc <- clump(rm, directions = 8, gaps = F) # gaps = F to prevent having missing numbers in the chunk numbers
  rc@data@max # return the highest chunk number
})