0

Let's assume that I have the following data set (named data set):

id  type    count
1   typeA   10
1   typeB   20
1   typeC   30
2   typeA   15
2   typeB   15
3   typeC   20

What will be the R code that'll produce the following table:

id  type_A  type_B  type_C
1   10       20       30
2   15       15       na
3   na       na       20
Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168
omer sagi
  • 701
  • 8
  • 11
  • 1
    That is the most basic reshaping problem and it could be solved in numerous trivial ways, for instance, `library(reshape2) ; dcast(df, id ~ type, value.var = "count")` – David Arenburg Jan 16 '15 at 11:58
  • See also [here](http://stackoverflow.com/questions/9617348/reshape-three-column-data-frame-to-matrix) – David Arenburg Jan 16 '15 at 12:01
  • It doesn't work in this case since it needs an aggregation function (assumes length as a default). – omer sagi Jan 16 '15 at 12:04
  • It works perfectly (tested on your data). If you want some other aggregation function, then just specify it within `dcast` – David Arenburg Jan 16 '15 at 12:22

1 Answers1

5

You can use tidyr:

library(tidyr)
spread(dat, type, count)

#   id typeA typeB typeC
# 1  1    10    20    30
# 2  2    15    15    NA
# 3  3    NA    NA    20

where dat is the name of your data frame.

Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168