我有一个栅格值(Raster包):
values(r)<-c(2,1,0,0,1,
1,1,1,0,0,
1,0,1,0,0,
2,1,0,1,0,
2,2,0,0,2)
我想在每个班级中找到clumps =补丁(值1,2)。不幸的是,clump(Raster)函数返回由O或NA值分隔的补丁,因此它将值1,2混合到单个补丁中。
另外,我想排除仅包含1个像素的补丁并将其设为NA,这可以用
values(rc)[!duplicated(values(rc)) & !duplicated(values(rc),fromLast=T)] <- NA
#(many thanks to @agstudy)
但是,我想排除仅包含1个像素但按类别值分隔的补丁(1,2)。
最后,我想获得:
values(r)<-c(NA,1,NA,NA,NA,
1,1,1,NA,NA,
1,NA,1,NA,NA,
2,NA,NA,1,NA,
2,2,NA,NA,NA)
代码示例:
library("raster")
r <- raster(ncols=5, nrows=5)
values(r)<-c(2,1,0,0,1,
1,1,1,0,0,
1,0,1,0,0,
2,1,0,1,0,
2,2,0,0,2)
答案 0 :(得分:2)
可能为时已晚,但我在处理同一主题时发现这个问题没有得到解答。
答案是遍历所有类值并分别对每个类进行聚集,同时填充带有NA的新栅格,其中块的频率为1(用于移除小块的原始代码:https://geoscripting-wur.github.io/AdvancedRasterAnalysis/#Applying_a_raster_sieve_by_clumping) 。通过将此NA光栅与原始光栅相乘,可以移除1个像素的色块。
请注意,我们必须展开栅格,否则左边和右边是'触摸',因为默认的x坐标是-180到180.最后,最终的栅格会被裁剪到原始范围。
# extend raster, otherwise left and right edges are 'touching'
r <- extend(r, c(1,1))
# get al unique class values in the raster
clVal <- unique(r)
# remove '0' (background)
clVal <- clVal[!clVal==0]
# create a 1-value raster, to be filled in with NA's
r.NA <- setValues(raster(r), 1)
# set background values to NA
r.NA[r==0]<- NA
# loop over all unique class values
for (i in clVal) {
# create & fill in class raster
r.class <- setValues(raster(r), NA)
r.class[r == i]<- 1
# clump class raster
clp <- clump(r.class)
# calculate frequency of each clump/patch
cl.freq <- as.data.frame(freq(clp))
# store clump ID's with frequency 1
rmID <- cl.freq$value[which(cl.freq$count == 1)]
# assign NA to all clumps whose ID's have frequency 1
r.NA[clp %in% rmID] <- NA
}
# multiply original raster by the NA raster
r <- r * r.NA
# crop the originally extended raster ((row 2-6 and column 2-6))
r <- crop(r, extent(r, 2, 6, 2, 6 ))
getValues(r)
# [1] NA 1 NA NA NA
# 1 1 1 NA NA
# 1 NA 1 NA NA
# 2 1 NA 1 NA
# 2 2 NA NA NA