将函数应用于每个子矩阵

时间:2014-12-30 14:38:22

标签: r matrix

我在R中寻找一个函数,比如apply,但是有子矩阵。我想做这样的事情:

原始矩阵:

    [,1] [,2] [,3] [,4]
[1,]    1    5    9   13
[2,]    2    6   10   14
[3,]    3    7   11   15
[4,]    4    8   12   16

函数后(每个2x2块的平均值):

        [,1]   [,2]  [,3]   [,4]
[1,]    3.5    3.5   11.5   11.5
[2,]    3.5    3.5   11.5   11.5
[3,]    5.5    5.5   13.5   13.5
[4,]    5.5    5.5   13.5   13.5

2 个答案:

答案 0 :(得分:4)

这是一种方式。它假设正在应用的函数返回一个标量,就像mean

的情况一样
A <- matrix(1:16, 4, 4)
k <- 2L

i <- (row(A) + 1L) %/% k        # row grouping
j <- (col(A) + 1L) %/% k        # col grouping
b <- i + (j - 1L) * max(i)      # block grouping
#      [,1] [,2] [,3] [,4]
# [1,]    1    1    3    3
# [2,]    1    1    3    3
# [3,]    2    2    4    4
# [4,]    2    2    4    4

subA <- split(A, b)             # sub-matrices
subm <- sapply(subA, mean)      # sub-means
out  <- array(subm[b], dim(A))  # final output
#      [,1] [,2] [,3] [,4]
# [1,]  3.5  3.5 11.5 11.5
# [2,]  3.5  3.5 11.5 11.5
# [3,]  5.5  5.5 13.5 13.5
# [4,]  5.5  5.5 13.5 13.5

答案 1 :(得分:0)

另一种选择是

ind <-  matrix(rep(1:2,each=2),4,4)+rep(c(0,2),each=8)
ave(A,ind)
#     [,1] [,2] [,3] [,4]
#[1,]  3.5  3.5 11.5 11.5
#[2,]  3.5  3.5 11.5 11.5
#[3,]  5.5  5.5 13.5 13.5
#[4,]  5.5  5.5 13.5 13.5

数据

A <-  matrix(1:16, 4, 4)