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

56,699

Solution 1

> 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
...

Solution 2

molten = melt( mydf , id.vars = c( "SN" , "class" ) , measure.vars = "myvar" )
casted = dcast( molten , SN~class )

Solution 3

Another approach with split:

mydfSplit <- split(mydf[,-2], mydf$class, drop=TRUE)

The result is a list which can be easily converted to a data.frame if the components have the same dimensions (which is true in this example):

mydf2 <- do.call(cbind, mydfSplit)

The problem with this solution is that the names of the final result need a cleaning. However, for a more general data, this can be useful if SN is different for each class.

Solution 4

In base R you could do it like this...

# get it sorted so that all you need to do is make a matrix out of it
mydf <- mydf[order(mydf$class, mydf$SN),]
# save the unique values of SN
SNu <- unique(mydf$SN)
# combine a matrix with SN
mydfw <- data.frame(SNu, matrix(mydf$myvar, nrow = length(SNu)))
# name your columns    
colnames(mydfw) <- c('SN', levels(mydf$class))

Or, for a more concise expression using aggregate

aggregate(myvar~SN, mydf, 'c')
# column names don't come out great
colnames(mydfw) <- c('SN', levels(mydf$class))
Share:
56,699
jon
Author by

jon

Updated on October 20, 2020

Comments

  • jon
    jon over 3 years

    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.