繁体   English   中英

如何在R中矩阵重塑

[英]How to matrix reshape in R

我得到了两个具有这种格式的大型矩阵:

row.names  1    2     3   ...          row.names  1    2   3  ....   

A          0.1 0.2 0.3                   A        1    1   1 
B          0.4 0.9 0.3                   B        2    3   1
C          0.9 0.9 0.4                   C        1    3   1
.

我想获得这样的东西:

X  S   CONF P
1  A   0.1  1
1  B   0.4  2
1  C   0.9  1
2  A   0.2  1
2  B  ......

在第一列中获取列名,并针对每个列名称重复行名和信息。

非常感谢

您可以通过一些repc工作轻松完成此操作:

out <- data.frame(X = rep(colnames(conf), each = nrow(conf)),
                  S = rep(rownames(conf), ncol(conf)),
                  CONF = c(conf), P = c(P))
out
#   X S CONF P
# 1 1 A  0.1 1
# 2 1 B  0.2 1
# 3 1 C  0.3 1
# 4 2 A  0.4 2
# 5 2 B  0.9 3
# 6 2 C  0.3 1
# 7 3 A  0.9 1
# 8 3 B  0.9 3
# 9 3 C  0.4 1

@Thomas也有类似的方法(但与您在问题中显示的答案相匹配的方法)。 他的回答如下:

cbind.data.frame(X = rep(colnames(conf), each=nrow(conf)),
                   S = rep(rownames(conf), times=nrow(conf)), 
                   CONF = matrix(t(conf), ncol=1),
                   P = matrix(t(P), ncol=1))

假设我们在谈论矩阵,我将转换为数据框,将行名添加为列,然后“融化”每个data.frame ...

conf <- matrix(
  c(0.1, 0.4, 0.9,
    0.2, 0.9, 0.9,
    0.3, 0.3, 0.4),
  ncol=3, byrow=T
)
rownames(conf) <- c("A", "B", "C")
colnames(conf) <- 1:3

P <- matrix(
  c(1, 2, 1,
    1, 3, 3,
    1, 1, 1),
  ncol=3, byrow=T
)
rownames(P) <- c("A", "B", "C")
colnames(P) <- 1:3

library(reshape)
conf <- cbind(as.data.frame(conf), "S"=rownames(conf))
P <- cbind(as.data.frame(P), "S"=rownames(P))
out <- merge(melt(conf, id="S"), melt(P, id="S"), by=c("variable", "S"))
colnames(out) <- c("X", "S", "CONF", "P")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM