在R中计算移动多数。

3
我正在尝试在R中计算栅格图像的移动多数值。栅格包中的focal函数只提供平均值、最小值和最大值。我有一个带有3个值(1、2和3)的栅格图像,我想要在中心设置一个3x3的窗口,并获得最常见的值。在R中,最有效的方法是什么?谢谢!
library(raster)

# create data
r <- raster(nrows = 120, ncol = 120, xmn=0)
r[] <- sample(3, ncell(r), replace=TRUE)
2个回答

4
你可以这样做:
f <- function(x){
 tab <- table(x)
 # I am using the first value here, maybe you want to use the mean, 
 # if 2 or more values occur equally often.
 names(tab)[which.max(tab)][1]
}

r <- raster(nrows = 120, ncol = 120, xmn=0)
r[] <- sample(3, ncell(r), replace=TRUE)

r <- focal(r, w=3, f)

好的方法。我在自制函数中使用了“table”来计算集合模式值。自然地,我现在找不到那段代码 :-( - Carl Witthoft
请注意,这种方法在terra中仍然有效,但是通过@maycca调用focalmodal不适用于raster之外。 - Jeffrey Evans

4
也许我有点晚了,但这对未来的读者可能还有用:
现在在R中,您可以找到大多数(模式)的focal函数,因此:
library(raster)

# create data
r <- raster(nrows = 120, ncol = 120, xmn=0)
r[] <- sample(3, ncell(r), replace=TRUE)

a<-focal(r, w=matrix(1,3,3), fun=modal)    # 3x3 moving window
plot(a)

注意:在使用NA值时要特别注意-最好将它们转换为整数。结果:来自焦点分析的结果

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接