数据帧变成对称矩阵,同时保留所有行和列

时间:2018-08-01 09:08:11

标签: r matrix

问题R DataFrame into square (symmetric) matrix是关于将数据帧转换为对称矩阵的示例,如下所示:

# data
x <- structure(c(1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0), 
                 .Dim = c(3L,5L), 
                 .Dimnames = list(c("X", "Y", "Z"), c("A", "B", "C", "D", "E")))

x
#  A B C D E
#X 1 1 0 0 0
#Y 1 1 0 0 0
#Z 0 0 0 1 0

# transformation
x <- x %*% t(x)
diag(x) <- 1

x
#  X Y Z
#X 1 2 0
#Y 2 1 0
#Z 0 0 1

现在,我正尝试将列c("A", "B", "C", "D", "E")保留在矩阵中,如下所示:

#  X Y Z A B C D E
#X 1 0 0 1 1 0 0 0
#Y 0 1 0 1 1 0 0 0
#Z 0 0 1 0 0 0 1 0
#A 1 1 0 1 0 0 0 0
#B 1 1 0 0 1 0 0 0
#C 0 0 0 0 0 1 0 0
#D 0 0 1 0 0 0 1 0
#E 0 0 0 0 0 0 0 1

我敢肯定,有一种简单的方法可以做到,类似于第一个包含每种情况的转换。有人可以提出解决方案吗?

提前谢谢!

2 个答案:

答案 0 :(得分:3)

这只是一种扩充,不是吗?

X <- as.matrix(x)
rbind(cbind(diag(nrow(X)), X), cbind(t(X), diag(ncol(X))))

答案 1 :(得分:1)

逐步构建它:感谢@李哲源指出m <- diag(sum(dim(x)))

m <- diag(sum(dim(x)))
colnames(m) = rownames(m) = c(rownames(x),colnames(x))
m[dimnames(x)[[1]],dimnames(x)[[2]]] <- x
m[dimnames(x)[[2]],dimnames(x)[[1]]] <- t(x)

#  X Y Z A B C D E
#X 1 0 0 1 1 0 0 0
#Y 0 1 0 1 1 0 0 0
#Z 0 0 1 0 0 0 1 0
#A 1 1 0 1 0 0 0 0
#B 1 1 0 0 1 0 0 0
#C 0 0 0 0 0 1 0 0
#D 0 0 1 0 0 0 1 0
#E 0 0 0 0 0 0 0 1

您可以将其包装到一个函数中,然后调用它:

makeSymMat <-function(x) {
    x <- as.matrix(x)
    m <- diag(sum(dim(x)))
    colnames(m) = rownames(m) = c(rownames(x),colnames(x))
    m[dimnames(x)[[1]],dimnames(x)[[2]]] <- x
    m[dimnames(x)[[2]],dimnames(x)[[1]]] <- t(x)
    return(m)
}

makeSymMat(x)