R中的滑动窗口功能 [英] Sliding window function in R

查看:313
本文介绍了R中的滑动窗口功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道R中是否存在2d矩阵的滑动窗口方法而不仅仅是向量。我需要将中位数函数应用于存储在矩阵中的图像

Does somebody know whether there is a sliding window method in R for 2d matrices and not just vectors. I need to apply median function to an image stored in matrix

推荐答案

函数 focal()栅格包中的code>对此有好处。除了以下示例中显示的参数之外,它还需要多个参数,并且如果需要,可以用于指定非矩形滑动窗口。

The function focal() in the excellent raster package is good for this. It takes several arguments beyond those shown in the example below, and can be used to specify a non-rectangular sliding window if that's needed.

library(raster)

## Create some example data
m <- matrix(1, ncol=10, nrow=10)
diag(m) <- 2
r <- as(m, "RasterLayer") # Coerce matrix to RasterLayer object

## Apply a function that returns a single value when passed values of cells
## in a 3-by-3 window surrounding each focal cell 
rmean <- focal(r, w=matrix(1/9, ncol=3, nrow=3), fun=mean)
rmedian <- focal(r, w=matrix(1/9, ncol=3, nrow=3), fun=median)

## Plot the results to confirm that this behaves as you'd expect
par(mfcol=c(1,3))
plot(r)
plot(rmean)
plot(rmedian)

## Coerce results back to a matrix, if you so desire
mmean <- as(rmean, "matrix")

这篇关于R中的滑动窗口功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆