Reorder the data in the table, the opposite of "melting",

I have a huge data size:

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 “not melt” the table with each level as one column and myvar in the fill:

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

How can I achieve this, I know this is a simple question, but I could not understand.

+42
r dataframe reshape
Oct 19 '11 at 20:37
source share
4 answers
 > 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 ... 
+43
Oct 19 '11 at 20:55
source share
 molten = melt( mydf , id.vars = c( "SN" , "class" ) , measure.vars = "myvar" ) casted = dcast( molten , SN~class ) 
+5
Oct 19 '11 at 20:59
source share

In the R database, you can 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 an aggregate

 aggregate(myvar~SN, mydf, 'c') # column names don't come out great colnames(mydfw) <- c('SN', levels(mydf$class)) 
+1
19 Oct '11 at 10:18
source share

Another split approach:

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

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

 mydf2 <- do.call(cbind, mydfSplit) 

The problem with this solution is that the final result names need to be cleaned up. However, for more general data, this may be useful if the SN for each class is different.

+1
Oct. 20 '11 at 9:59 a.m.
source share



All Articles