Transpose data by groups in R

Tomas Greif picture Tomas Greif · Jun 29, 2013 · Viewed 13.8k times · Source

I have data in the following structure:

x <- read.table(header=T, text="
X Y D S
a e 1 10
a e 2 20
a f 1 50
b c 1 40
b c 2 30
b c 3 60
b d 1 10 
b d 2 20")

And I want to get the following result:

X Y   1   2   3
a e  10  20
a f  50
b c  40  30  60
b d  10  20

For every combination of columns X and Y I would like to transpose data in column S by order in column D.

I thought xtabs() will work, but I don't think so, my best version is:

xtabs(formula=S~Y+D,data=x)

With result:

   D
Y    1  2  3
  c 40 30 60
  d 10 20  0
  e 10 20  0
  f 50  0  0

Answer

Arun picture Arun · Jun 29, 2013
require(reshape2)
dcast(x, X + Y ~ D, value.var="S")

If you want to fill empty entries with 0 instead of NA (which is the default), then,

dcast(x, X + Y ~ D, value.var="S", fill=0)