从置换向量生成置换矩阵

时间:2015-10-01 01:44:51

标签: r permutation

假设我有一个置换向量(行置换)

x <- c(1,2,3,4,7,8,5,6,9,10) # I exchanged 7 with 5 and 8 with 6.

R中是否有任何函数可以从置换向量生成相应的置换矩阵?如果是这样,请举个例子。

2 个答案:

答案 0 :(得分:2)

我相信这可以通过重新排序单位矩阵的行来完成:

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

答案 1 :(得分:2)

也可以使用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)