将矩阵转换为列

时间:2016-12-07 15:58:17

标签: r matrix

假设我的矩阵如下所示,对角线上下的值是相同的。换句话说,[,1] x [2,]和[,2] x [1,]在矩阵中都是2。

> m = cbind(c(1,2,3),c(2,4,5),c(3,5,6))
> m
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    2    4    5
[3,]    3    5    6

然后我也有1,2和3的真实姓名。

>Real_name
A B C   # A represents 1, B represents 2, and C represents 3.

如果我想将矩阵转换为包含每对的相应实名的3列,并且该对必须是唯一的,则A x B与B x A相同,因此我们仅保留A x B.如何使用R实现它?

A A 1
A B 2 
A C 3 
B B 4 
B C 5
C C 6

3 个答案:

答案 0 :(得分:3)

以下是直截了当的:

m <- cbind(c(1,2,3), c(2,4,5), c(3,5,6))
## read `?lower.tri` and try `v <- lower.tri(m, diag = TRUE)` to see what `v` is
## read `?which` and try `which(v, arr.ind = TRUE)` to see what it gives
ij <- which(lower.tri(m, diag = TRUE), arr.ind = TRUE)

Real_name <- LETTERS[1:3]
data.frame(row = Real_name[ij[, 1]], col = Real_name[ij[, 2]], val = c(m[ij]))

#  row col val
#1   A   A   1
#2   B   A   2
#3   C   A   3
#4   B   B   4
#5   C   B   5
#6   C   C   6

答案 1 :(得分:3)

colnames(m) <- c("A", "B", "C")
rownames(m) <- c("A", "B", "C")

m[lower.tri(m)] = NA                   # replace lower triangular elements with NA
data.table::melt(m, na.rm = TRUE)        # melt and remove NA

#  Var1 Var2 value
#1    A    A     1
#4    A    B     2
#5    B    B     4
#7    A    C     3
#8    B    C     5
#9    C    C     6

或者您可以在一行中完成:melt(replace(m, lower.tri(m), NA), na.rm = TRUE)

答案 2 :(得分:0)

这也有效:

g <- expand.grid(1:ncol(m), 1:ncol(m))
g <- g[g[,2]>=g[,1],] 
cbind.data.frame(sapply(g, function(x) Real_name[x]), Val=m[as.matrix(g)])

  Var1 Var2 Val
1    A    A   1
2    A    B   2
3    B    B   4
4    A    C   3
5    B    C   5
6    C    C   6