如何组合来自不同列的数据,例如给定列的周围列的平均值

时间:2014-04-28 09:30:44

标签: r matrix smoothing

我试图通过将覆盖 n 列的窗口的平均值归因于给定列来平滑矩阵。我设法做到了,但我想看看R' R''这样做,因为我正在使用for循环。有没有办法使用apply或同一家族的某些功能来获得此功能?

示例:

# create a toy matrix
mat <- matrix(ncol=200);
for(i in 1:100){ mat <- rbind(mat,sample(1:200, 200) )}
# quick visualization
image(t(mat))

enter image description here

这是平滑前的矩阵:

我编写了函数smooth_mat,它采用矩阵和平滑内核的长度:

smooth_row_mat <- function(k, k.d=5){
    k.range <- (k.d + 2):(ncol(k) - k.d - 1)
    k.smooth <- matrix(nrow=nrow(k))
    for( i in k.range){
            if (i  %% 10 == 0)      cat('\r',round(i/length(k.range), 2))
            k.smooth <- cbind( k.smooth, rowMeans(k[,c(  (i-1-k.d):(i-1) ,i, (i+1):(i + 1 - k.d) )]) )
    }
    return(k.smooth)

}

现在我们将smooth_row_mat()mat

一起使用
mat.smooth <- smooth_mat(mat)

我们已经成功地连续平滑了矩阵的内容。

这是以下矩阵: enter image description here

这种方法适用于这么小的矩阵,虽然我的真实矩阵大约是40,000 x 400,但仍然有效,但我想提高我的R技能。

谢谢!

2 个答案:

答案 0 :(得分:2)

以下是我使用raster包的方式。

首先,创建一个填充随机数据的矩阵,并将其强制转换为raster对象。

library(raster)
r <- raster(matrix(sample(200, 200*200, replace=TRUE), nc=200))
plot(r)

enter image description here

然后使用focal函数计算焦点单元两侧n个细胞邻域的邻域均值。您提供给focal函数的权重矩阵中的值确定每个单元格的值对焦点摘要的贡献程度。对于平均值,我们说我们希望每个单元格都贡献1/n,因此我们填充n列的矩阵,其值为1/n。请注意,n必须是奇数,并且矩阵中心的单元格被视为焦点单元格。

n <- 3
smooth_r <- focal(r, matrix(1/n, nc=n))
plot(smooth_r)

enter image description here

答案 1 :(得分:2)

您可以在矩阵的每一行中应用过滤器(运行平均值),如下所示:

apply(k, 1, filter, rep(1/k.d, k.d))