Вопрос

I got two large matrix with this format:

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
.

And I want to obtain something like this:

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  ......

Getting the colnames in one column and repeat the rownames and the information per each of the column names.

Thank you so much

Это было полезно?

Решение

You can do this pretty easily with some rep and c work:

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 had a similar approach (but one which matches the answer you show in your question). His answer looked like this:

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))

Другие советы

Assuming we're talking about matrices, I would convert to a data frame, add the rownames as a column and then "melt" each 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 с атрибуция
Не связан с StackOverflow
scroll top