计算R中的移动多数

时间:2012-06-19 14:04:25

标签: r

我正在尝试计算R中栅格上的移动多数值。栅格包中的焦点函数只提供均值,最小值和最大值。我有一个有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 个答案:

答案 0 :(得分: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)

答案 1 :(得分:4)

也许我有点迟了,但它对未来读者可能有用:

现在在R中你可以找到多数(模式)的焦点功能,所以:

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值时要注意 - 最好将它们转换为整数)

结果:

result from focal analysis