【问题标题】:Summing up different elements in a matrix in R总结R中矩阵中的不同元素
【发布时间】:2021-01-26 16:46:00
【问题描述】:

我正在尝试对 R 中矩阵中的不同元素执行计算。我的矩阵是 18x18,我想得到例如每个 6x6 数组的平均值(总共 9 个数组)。我想要的数组是:

A1 <- df[1:6,1:6]
A2 <- df[1:6,7:12]
A3 <- df[1:6,13:18]
B1 <- df[7:12,1:6]
B2 <- df[7:12,7:12]
B3 <- df[7:12,13:18]
C1 <- df[13:18,1:6]
C2 <- df[13:18,7:12]
C3 <- df[13:18,13:18]

矩阵如下所示:

    5   10  15  20  25  30  35  40  45  50  55  60  65  70  75  80  85  90
5   14  17  9   10  8   4   10  12  18  9   13  14  NA  NA  19  15  10  10
10  30  32  23  27  17  28  25  12  28  29  28  26  19  25  34  24  11  17
15  16  16  16  9   17  27  17  16  30  13  18  13  15  13  19  8   7   9
20  15  12  18  18  18  6   4   6   9   11  10  10  13  11  8   10  15  15
25  7   13  21  7   3   5   2   5   5   4   3   2   3   5   2   1   5   6
30  5   9   1   7   7   4   4   12  8   9   2   0   5   2   1   0   2   6
35  3   0   2   0   0   4   4   7   4   4   5   2   0   0   1   0   0   0
40  0   4   0   0   0   1   3   9   10  10  1   0   0   0   1   0   1   0
45  0   0   0   0   0   3   10  9   17  9   1   0   0   0   0   0   0   0
50  0   0   2   0   0   0   2   8   20  0   0   0   0   0   1   0   0   0
55  0   0   0   0   0   0   7   3   21  0   0   0   0   0   0   0   0   0
60  0   0   0   0   3   4   10  2   2   0   0   1   0   0   0   0   0   0
65  0   0   0   0   0   4   8   4   8   11  0   0   0   0   0   0   0   0
70  0   0   0   0   0   6   2   5   14  0   0   0   0   0   0   0   0   0
75  0   0   0   0   0   4   0   5   9   0   0   0   0   0   0   0   0   0
80  0   0   0   0   0   4   4   0   4   2   0   0   0   0   0   0   0   0
85  0   0   0   0   0   0   0   4   1   1   0   0   0   0   0   0   0   0
90  0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0

有没有一种干净的方法可以用循环解决这个问题?

非常感谢,

保罗

【问题讨论】:

  • 将您的子矩阵放入列表 matlist 并使用 sapply: means &lt;- sapply(matlist, mean)

标签: r matrix


【解决方案1】:

给定你的矩阵,例如

x <- matrix(1:(18*18), ncol=18)

尝试,例如对于 6 的子矩阵

step <- 6

nx <- nrow(x)
if((nx %% step) != 0) stop("nx %% step should be 0") 

indI <- seq(1, nx, by=step)
nbStep <- length(indI)

for(Col in 1:nbStep){
  for(Row in 1:nbStep){
    name <- paste0(LETTERS[Col],Row)
    theCol <- indI[Col]:(indI[Col]+step-1)
    theRow <- indI[Row]:(indI[Row]+step-1)
    assign(name, sum(x[theCol, theRow]))
  }
}

您将获得 A1、A2、A3 的成绩... 这就是想法。扭曲非方阵的代码,不同大小的子矩阵,...

【讨论】:

  • 非常感谢大家的真诚和快速的建议。这对我帮助很大!
【解决方案2】:

这是一种方法:

# generate fake data
set.seed(47)
n = 18
m = matrix(rpois(n * n, lambda = 5), nrow = n)

# generate starting indices
n_array = 6
start_i = seq(1, n, by = n_array)
arr_starts = expand.grid(row = start_i, col = start_i)

# calculate sums
with(arr_starts, mapply(function(x, y) sum(m[(x + 1:n_array) - 1, (y + 1:n_array) - 1]), row, col))
# [1] 158 188 176 201 188 201 197 206 204

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-29
    • 2014-12-31
    • 1970-01-01
    • 2014-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多