0

I have the following data.frame in R.

(df1 <- data.frame(col1=rep(c('a','b','c'),each=3),
                   col2=rep(c('d','e','f'),3),
                   col3=1:9))

  col1 col2 col3
1    a    d    1
2    a    e    2
3    a    f    3
4    b    d    4
5    b    e    5
6    b    f    6
7    c    d    7
8    c    e    8
9    c    f    9

And I want to transform it into the following format.

  d e f
a 1 2 3
b 4 5 6
c 7 8 9

What's the easiest way to do that?

Rodrigo
  • 4,706
  • 6
  • 51
  • 94

1 Answers1

2

One option is xtabs

xtabs(col3~ col1 + col2, df1)

Or using acast

reshape2::acast(df1, col1 ~ col2)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thank you, but how do I convert it from xtabs to a data.frame or matrix class? – Rodrigo Jul 05 '18 at 02:09
  • 1
    @Rodrigo If you want a data.frame wrap with `as.data.frame.matrix` and the `acast` output is a `matrix`. `xtabs` is also a `matrix` with `xtabs` attribute which we can remove it if needed – akrun Jul 05 '18 at 02:10
  • 1
    e.g. if `out <- xtabs(col3 ~ col1 + col2, df1); class(out) <- "matrix"; attr(out, "call") <- NULL; names(dimnames(out)) <- NULL` or convert to sparse and then reconvert to `matrix` i.e. `out <- xtabs(col3 ~ col1 + col2, df1, sparse = TRUE); as.matrix(out)` – akrun Jul 05 '18 at 02:19
  • 1
    Awesome! Thank you for another lesson. – Rodrigo Jul 05 '18 at 02:40