假设我有一个排列向量(行排列)
x <- c(1,2,3,4,7,8,5,6,9,10) # I exchanged 7 with 5 and 8 with 6.
R中是否有函数可以从排列向量生成相应的排列矩阵?如果是的话,请给我一个例子。
我相信这可以通过重新排序单位矩阵的行来完成:
x <- c(1,2,3,4,7,8,5,6,9,10)
diag(length(x))[x,]
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
# [1,] 1 0 0 0 0 0 0 0 0 0
# [2,] 0 1 0 0 0 0 0 0 0 0
# [3,] 0 0 1 0 0 0 0 0 0 0
# [4,] 0 0 0 1 0 0 0 0 0 0
# [5,] 0 0 0 0 0 0 1 0 0 0
# [6,] 0 0 0 0 0 0 0 1 0 0
# [7,] 0 0 0 0 1 0 0 0 0 0
# [8,] 0 0 0 0 0 1 0 0 0 0
# [9,] 0 0 0 0 0 0 0 0 1 0
# [10,] 0 0 0 0 0 0 0 0 0 1
这也可以用
sparseMatrix
来完成
library(Matrix)
m1 <- sparseMatrix(seq_along(v1), v1, x=1)
我们可以使用
matrix
将其强制为
as.matrix
as.matrix(m1)
v1 <- c(1,2,3,4,7,8,5,6,9,10)
这就是人们可以在基础 R 中简单地做的事情(无包)。
让我们开始设置一些矩阵进行排列。
# Let us assume your nxn-matrix is
n <- 3
(M <- matrix(as.numeric(1:(n*n)), n))
# [,1] [,2] [,3]
#[1,] 1 4 7
#[2,] 2 5 8
#[3,] 3 6 9
对于单个置换矩阵,基于随机向量置换(枢轴),我们有:
## To generate the permutation matrix associated to a random 1:n permutation:
vperm <- sample(1:n)
(mperm <- Reduce(\(m,i) `[[<-`(m, i, vperm[i], 1), 1:n, matrix(0, n, n)))
# [,1] [,2] [,3]
#[1,] 0 1 0
#[2,] 1 0 0
#[3,] 0 0 1
## To permute the columns of M:
t(mperm) %*% M
# [,1] [,2] [,3]
#[1,] 2 5 8
#[2,] 1 4 7
#[3,] 3 6 9
## And, to permute the rows of M:
M %*% mperm
# [,1] [,2] [,3]
#[1,] 4 1 7
#[2,] 5 2 8
#[3,] 6 3 9
现在,我们生成所有可能的主元向量和相关的置换矩阵
## To generate all possible random 1:n permutations:
vdisps <- expand.grid(rep(list(1:n), n)) # with repetitions
vperms <- Filter(\(v) length(unique(t(v))) == n, split(vdisps, 1:n^n))
## To generate the permutation matrices associated to each random permutation:
mperms <- lapply(vperms, \(permdf)
Reduce(\(m,i) `[[<-`(m, i, permdf[[i]], 1), 1:n, matrix(0, n, n)))
## The related list of column-permutated matrices are
lapply(mperms, \(P) t(P) %*% M)
当然,这是R,所以我们可以使用它的子集功能。
## Given
oo <- order(vperm) #,
## we can replace t(mperm) %*% M with:
identical(t(mperm) %*% M, M[oo, ]) # TRUE
identical(M %*% mperm, M[, oo]) # TRUE
这是使用带有
chol(..., pivot = TRUE)
的 Cholesky 分解时建议执行的操作。
NB
as.numeric()
很重要,在生成 M
时,让 identical()
发挥作用。