4

How can I turn the following matrix (or table/data frame) with row names & column names,

    A       B
M   27143   18324
F   29522   18875

into something like

27143  M  A
18324  M  B
29522  F  A
18875  F  B

so that I can do some analysis in R?

Alby
  • 5,522
  • 7
  • 41
  • 51

2 Answers2

9

You can use the reshape2 package and melt the data.

temp = read.table(header=TRUE, text="    A       B
M   27143   18324
F   29522   18875")
library(reshape2)
temp$id = rownames(temp)
melt(temp)
# Using id as id variables
# id variable value
# 1  M        A 27143
# 2  F        A 29522
# 3  M        B 18324
# 4  F        B 18875
A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485
  • Thank you for this! exactly what I was looking for. Just out of curiosity, is there a way to revert the process? in other words, "un-melt" it? – Alby Jul 16 '12 at 21:00
  • found it! dcast or acast was the answer – Alby Jul 16 '12 at 21:41
1

You can also use data.tableto add the row names as first column then you melt it based on their row names

df<- structure(list(A = c(27143L, 29522L), B = c(18324L, 18875L)), .Names = c("A", 
"B"), class = "data.frame", row.names = c("M", "F"))

library(data.table)
library(reshape2)
setDT(df, keep.rownames = TRUE)[]

#   rn     A     B
#1:  M 27143 18324
#2:  F 29522 18875

(melt(df, id.vars="rn"))
#   rn variable value
#1:  M        A 27143
#2:  F        A 29522
#3:  M        B 18324
#4:  F        B 18875

Or use gather instead melt

library(tidyr)
gather(df, "rn")
#  rn rn value
#1  M  A 27143
#2  F  A 29522
#3  M  B 18324
#4  F  B 18875