Rearrange dataframe to a table, the opposite of "melt"

jon picture jon · Oct 19, 2011 · Viewed 49k times · Source

I have huge dataframe like this:

SN = c(1:100, 1:100, 1:100, 1:100)  
class = c(rep("A1", 100), rep("B2", 100), rep("C3", 100), rep("D4", 100)) # total 6000 levels 
myvar = rnorm(400)
mydf = data.frame(SN, class, myvar) 

I want to "unmelt" to a table with each level as single column and myvar in filled:

SN          A1            B2          C3         D4       .............and so on for all 6000 

How can I achieve this, I know it is simple question, but I could not figure out.

Answer

John Colby picture John Colby · Oct 19, 2011
> dcast(mydf, SN ~ class)

  SN         A1         B2          C3          D4
1  1  0.1461258  0.8325014  0.33562088 -0.07294576
2  2  0.5964182  0.4593710 -0.23652803 -1.52539568
3  3  2.0247742 -1.1235963  1.79875447 -1.87462227
4  4  0.8184004  1.3486721  0.76076486 -1.18311991
5  5 -0.6577212  0.3666741 -0.06057506  1.38825487
6  6  0.1590443  0.2043661  0.08161778  0.10421797
...