3

I have a matrix such as:

> mt <- matrix(1:9, nrow=3, ncol=3)
> dimnames(mt) <- list( c('a','b','c'), c('x','y','z') )
> mt
  x y z
a 1 4 7
b 2 5 8
c 3 6 9

I can convert it into a tabular format with:

> as.data.frame(as.table(mt))
  Var1 Var2 Freq
1    a    x    1
2    b    x    2
3    c    x    3
4    a    y    4
5    b    y    5
6    c    y    6
7    a    z    7
8    b    z    8
9    c    z    9

My question is - Is there a clean way to do the reverse?

Frank
  • 66,179
  • 8
  • 96
  • 180
tinkerbeast
  • 1,707
  • 1
  • 20
  • 42

2 Answers2

2

You can use: ?xtabs :Create a contingency table (optionally a sparse matrix) from cross-classifying factors, usually contained in a data frame, using a formula interface.

 xtabs(Freq~Var1+Var2,Data)
    Var2
Var1 x y z
   a 1 4 7
   b 2 5 8
   c 3 6 9  

You can also use this : ?acsat:Use acast or dcast depending on whether you want vector/matrix/array output or data frame output. Data frames can have at most two dimensions.

library(reshape2)
zz <- "Var1 Var2 Freq
1    a    x    1
2    b    x    2
3    c    x    3
4    a    y    4
5    b    y    5
6    c    y    6
7    a    z    7
8    b    z    8
9    c    z    9"
Data <- read.table(text=zz, header = TRUE)

acast(Data, Var1 ~ Var2)
Using Freq as value column: use value.var to override.
  x y z
a 1 4 7
b 2 5 8
c 3 6 9  
Prasanna Nandakumar
  • 4,295
  • 34
  • 63
1

How about reshape2::acast:

require(reshape2)
acast(m,Var1~Var2)

#  x y z
#a 1 4 7
#b 2 5 8
#c 3 6 9

ps: you can use reshape2::melt() to go the other way

Troy
  • 8,581
  • 29
  • 32