对 R 中的矩阵重复一个简单的算法?
Repeating a simple algorithm for matrices in R?
我试图通过创建第一部分 来避免重复一些简单的计算。但是我想知道为什么我没有得到与 second part 相同的结果(第二部分给出了正确答案)?
第一部分:
a = matrix(c(8,11,2, 6,8,4, 4,5,6, 2,8,8), nrow = 3)
nr = nrow(a)
nc = ncol(a)
mc = colMeans(a)
mr = rowMeans(a)
gr = mean(a)
(m = matrix(c(a[rep(1:nr, nr), rep(1:nc, each = nc)] - mr[rep(1:nr, nr)] -
mc[rep(1:nc, each = nc)] + gr), nrow = nr, ncol = nc)) ## This is NOT correct answer !!
第二部分:
a11 <- a[1, 1] - mr[1] - mc[1] + gr
a21 <- a[2, 1] - mr[2] - mc[1] + gr
a31 <- a[3, 1] - mr[3] - mc[1] + gr
a12 <- a[1, 2] - mr[1] - mc[2] + gr
a22 <- a[2, 2] - mr[2] - mc[2] + gr
a32 <- a[3, 2] - mr[3] - mc[2] + gr
a13 <- a[1, 3] - mr[1] - mc[3] + gr
a23 <- a[2, 3] - mr[2] - mc[3] + gr
a33 <- a[3, 3] - mr[3] - mc[3] + gr
a14 <- a[1, 4] - mr[1] - mc[4] + gr
a24 <- a[2, 4] - mr[2] - mc[4] + gr
a34 <- a[3, 4] - mr[3] - mc[4] + gr
g = paste0("a", rep(1:3, 3), rep(1:4, each = 3))
(m = matrix(c(mget(g)), nr = 3, ncol = 4)) ## This is the correct answer !!
可能与 R 处理矩阵的方式有关。
m = matrix(c(1,2,3,4), nrow =2)
矩阵由列填充,所以在我的例子中:
$$ \begin{pmatrix}
1 & 3 \
2 & 4
\end{pmatrix} $$
如果你希望它不是这样,你可以这样指定:
m = matrix(c(1,2,3,4),nrow = 2, byrow = TRUE)
应该可以。
您可以使用outer
来计算差异:
myMat <- a - outer(mr, mc, "+") + gr
myMat
[,1] [,2] [,3] [,4]
[1,] 2 1 0 -3
[2,] 2 0 -2 0
[3,] -4 -1 2 3
重建 m 使其不是列表
m = matrix(unlist(mget(g)), nr = 3, ncol = 4)
现在,检查它们是否相同:
identical(m, myMat)
[1] TRUE
我试图通过创建第一部分 来避免重复一些简单的计算。但是我想知道为什么我没有得到与 second part 相同的结果(第二部分给出了正确答案)?
第一部分:
a = matrix(c(8,11,2, 6,8,4, 4,5,6, 2,8,8), nrow = 3)
nr = nrow(a)
nc = ncol(a)
mc = colMeans(a)
mr = rowMeans(a)
gr = mean(a)
(m = matrix(c(a[rep(1:nr, nr), rep(1:nc, each = nc)] - mr[rep(1:nr, nr)] -
mc[rep(1:nc, each = nc)] + gr), nrow = nr, ncol = nc)) ## This is NOT correct answer !!
第二部分:
a11 <- a[1, 1] - mr[1] - mc[1] + gr
a21 <- a[2, 1] - mr[2] - mc[1] + gr
a31 <- a[3, 1] - mr[3] - mc[1] + gr
a12 <- a[1, 2] - mr[1] - mc[2] + gr
a22 <- a[2, 2] - mr[2] - mc[2] + gr
a32 <- a[3, 2] - mr[3] - mc[2] + gr
a13 <- a[1, 3] - mr[1] - mc[3] + gr
a23 <- a[2, 3] - mr[2] - mc[3] + gr
a33 <- a[3, 3] - mr[3] - mc[3] + gr
a14 <- a[1, 4] - mr[1] - mc[4] + gr
a24 <- a[2, 4] - mr[2] - mc[4] + gr
a34 <- a[3, 4] - mr[3] - mc[4] + gr
g = paste0("a", rep(1:3, 3), rep(1:4, each = 3))
(m = matrix(c(mget(g)), nr = 3, ncol = 4)) ## This is the correct answer !!
可能与 R 处理矩阵的方式有关。
m = matrix(c(1,2,3,4), nrow =2)
矩阵由列填充,所以在我的例子中:
$$ \begin{pmatrix} 1 & 3 \ 2 & 4 \end{pmatrix} $$
如果你希望它不是这样,你可以这样指定:
m = matrix(c(1,2,3,4),nrow = 2, byrow = TRUE)
应该可以。
您可以使用outer
来计算差异:
myMat <- a - outer(mr, mc, "+") + gr
myMat
[,1] [,2] [,3] [,4]
[1,] 2 1 0 -3
[2,] 2 0 -2 0
[3,] -4 -1 2 3
重建 m 使其不是列表
m = matrix(unlist(mget(g)), nr = 3, ncol = 4)
现在,检查它们是否相同:
identical(m, myMat)
[1] TRUE