2

Help please !

I have a large matrix and I would like to rearrange the data (or shall i call deconstruction of a martix ?)

    M1   M2   M3   M4  
L1 "AA" "--" "GG" "CC"
L2 "AG" "CC" "--" "AA"
L3 "GG" "CG" "TT" "TT"
L4 "--" "GG" "CC" "TT"
L5 "AA" "--" "AA" "CC"
L6 "AT" "CC" "CT" "AA"
L7 "TT" "CG" "TA" "CC"

the sample data is

test <- matrix(c("AA", "AG", "GG", "--","AA", "AT", "TT", "--","CC", "CG", "GG", "--","CC", "CG", "GG", "--","TT","CC","AA","CT","TA","CC","AA","TT","TT","CC","AA","CC"),nrow=7)
row.names(test)= c("L1", "L2", "L3", "L4", "L5", "L6", "L7")
colnames(test)= c("M1", "M2", "M3", "M4")

I need to rearrange and get the data in following format

Line Marker testx
L1     M1    AA
L1     M2    --
L1     M3    GG
L1     M4    CC
L2     M1    AG
L2     M2    CC
L2     M3    --
L2     M4    AA
L3     M1    GG
L3     M2    CG
L3     M3    TT
L3     M4    TT
.
.
.

Though I have a lengthy solution (see below), it is hard while handling large dataset. Please help me!

testx<-c(test)
testx1<-data.frame(testx)
testx2<-cbind(Line = c("L1","L2","L3","L4","L5","L6","L7"), testx1)
testx3<-testx2[order(testx2$Line),]
testx4<-cbind(Marker = c("M1","M2","M3","M4"), testx3)
testx5 <- testx4[,c("Line", "Marker", "testx")]
1
  • A classic approach in such cases is as.data.frame(as.table(test)). Check out, also, for its extreme handiness, xtabs which is the exact opposite when the column with values is "numeric".
    – alexis_laz
    Jul 10, 2014 at 15:49

3 Answers 3

2

The easiest way I can think of would be to use melt from "reshape2":

library(reshape2)
melt(test)
#    Var1 Var2 value
# 1    L1   M1    AA
# 2    L2   M1    AG
# 3    L3   M1    GG
# 4    L4   M1    --
# 5    L5   M1    AA
## <<SNIP>>
# 23   L2   M4    AA
# 24   L3   M4    TT
# 25   L4   M4    TT
# 26   L5   M4    CC
# 27   L6   M4    AA
# 28   L7   M4    CC

From there, just use order to get the required order for "Var1" and "Var2".

1
data.frame(Line=rep(row.names(test), each=ncol(test)), Marker=rep(colnames(test), times = nrow(test)), testx=c(t(test)) )
0

You can use the package tidyr rather than reshape2, if you first convert your matrix to a data.frame.

  library(tidyr)
  library(dplyr) ## for arrange()

  test1 <- data.frame(Line = rownames(test),test)

  test2 <- gather(test1,Marker,testx,M1:M4)

  head(arrange(test2,Line,Marker))

  Line Marker testx
1   L1     M1    AA
2   L1     M2    --
3   L1     M3    GG
4   L1     M4    CC
5   L2     M1    AG
6   L2     M2    CC

The last step, arrange, is simply to sort the data as in your example. As @Ananda pointed out, you can easily do the same with order, e.g.

test2[order(test2$Line,test2$Marker),]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.