这是一个没有多边形化的解决方案:(它不优雅,但它有效)。但是,您必须将孔/岛重新分类为值(即 999)和所有其他非岛到 NA。像这样:
x <- raster(x=matrix(rep(NA,36), nrow=6), xmn=-1000, xmx=1000, ymn=-100, ymx=900)
x[c(8, 15, 16, 17, 22, 25, 26, 30, 31)] <- 999
plot(x)

现在我使用这个clump()
函数来检查是否有岛,这个函数很酷的是,它还返回这些岛的 ID:
#Get Islands with IDs
cl <- clump(x,directions=8)
plot(cl)

然后我根据岛屿的频率创建一个数据框(这只是为了获取每个岛屿的 ID)
freqCl <- as.data.frame(freq(cl))
#remove the (row) which corresponds to the NA values (this is important for the last step)
freqCl <- freqCl[-which(is.na(freqCl$value)),]
检查是否有任何岛屿接触边界:
#Check if the island touches any border and therefore isn't a "real island" (first and last column or row)
noIslandID <- c()
#First row
if(any(rownames(freqCl) %in% cl[1,])){
eliminate <- rownames(freqCl)[rownames(freqCl) %in% cl[1,]]
noIslandID <- append(noIslandID, eliminate)
}
#Last row
if(any(rownames(freqCl) %in% cl[nrow(cl),])){
eliminate <- rownames(freqCl)[rownames(freqCl) %in% cl[nrow(cl),]]
noIslandID <- append(noIslandID, eliminate)
}
#First col
if(any(rownames(freqCl) %in% cl[,1])){
eliminate <- rownames(freqCl)[rownames(freqCl) %in% cl[,1]]
noIslandID <- append(noIslandID, eliminate)
}
#Last col
if(any(rownames(freqCl) %in% cl[,ncol(cl)])){
eliminate <- rownames(freqCl)[rownames(freqCl) %in% cl[,ncol(cl)]]
noIslandID <- append(noIslandID, eliminate)
}
消除那些接触边界的岛屿:
noIslandID <- unique(noIslandID)
IslandID <- setdiff(rownames(freqCl), noIslandID)
在最后一步,为初始栅格中的每个“真实岛屿”分配 1:
for(i in 1:length(IslandID)) {
x[cl[]==as.numeric(IslandID[i])] <- 1
}
plot(x)
