将数组重塑为距离矩阵(在 R 中)
Reshape array into distance matrix (in R)
我有一个数组,它是通过展平对称方阵(即距离矩阵)的底部三角形生成的。我希望反转该过程并从数组生成完整的方阵。
假设原始矩阵是:
0 1 2 4
1 0 3 5
2 3 0 6
4 5 6 0
下三角是:
1
2 3
4 5 6
...然后将其展平并记录为数组
1 2 3 4 5 6
我想获取该数组并将其转换回原始矩阵。我希望它会像
一样简单
as.matrix(as.dist(ar)) + t(as.matrix(as.dist(ar)))
...但 as.dist(...)
实际上继续以各种方式计算距离,而不是简单地填充数组中的值。可能有一个简单的替代方案,对吧?
ar <- 1:6
d <- (1 + sqrt(1 + 8 * length(ar))) / 2
x <- matrix(0, d, d)
x[upper.tri(x)] <- ar
x[lower.tri(x)] <- t(x)[lower.tri(x)]
x
# [,1] [,2] [,3] [,4]
# [1,] 0 1 2 4
# [2,] 1 0 3 5
# [3,] 2 3 0 6
# [4,] 4 5 6 0
设n1
使得1+2+3+...+n1是x
的长度并设n=n1+1。那么m
是一个n x n 矩阵所以:
ar <- 1:6
n <- which(cumsum(seq_along(ar)) == length(ar)) + 1
m <- matrix(0, n, n)
as.dist(t(replace(m, upper.tri(m), ar)))
给予:
1 2 3
2 1
3 2 3
4 4 5 6
我有一个数组,它是通过展平对称方阵(即距离矩阵)的底部三角形生成的。我希望反转该过程并从数组生成完整的方阵。
假设原始矩阵是:
0 1 2 4
1 0 3 5
2 3 0 6
4 5 6 0
下三角是:
1
2 3
4 5 6
...然后将其展平并记录为数组
1 2 3 4 5 6
我想获取该数组并将其转换回原始矩阵。我希望它会像
一样简单as.matrix(as.dist(ar)) + t(as.matrix(as.dist(ar)))
...但 as.dist(...)
实际上继续以各种方式计算距离,而不是简单地填充数组中的值。可能有一个简单的替代方案,对吧?
ar <- 1:6
d <- (1 + sqrt(1 + 8 * length(ar))) / 2
x <- matrix(0, d, d)
x[upper.tri(x)] <- ar
x[lower.tri(x)] <- t(x)[lower.tri(x)]
x
# [,1] [,2] [,3] [,4]
# [1,] 0 1 2 4
# [2,] 1 0 3 5
# [3,] 2 3 0 6
# [4,] 4 5 6 0
设n1
使得1+2+3+...+n1是x
的长度并设n=n1+1。那么m
是一个n x n 矩阵所以:
ar <- 1:6
n <- which(cumsum(seq_along(ar)) == length(ar)) + 1
m <- matrix(0, n, n)
as.dist(t(replace(m, upper.tri(m), ar)))
给予:
1 2 3
2 1
3 2 3
4 4 5 6