Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reversing a melting operation with reshape2 [duplicate]

Tags:

r

reshape2

Consider the following code.

library (reshape2)
x = rnorm (20)
y = x + rnorm (rnorm (20, sd = .01))

dfr <- data.frame (x, y)
mlt <- melt (dfr)

When I try to reverse this operation with dcast,

dcast (mlt, value ~ variable)

I get instead a data frame with three columns (not suitable for scatter-plotting, for instance). How can I reenact the original data frame with dcast?

like image 401
Gil Tomás Avatar asked Apr 09 '13 14:04

Gil Tomás


People also ask

What is the opposite of melt in R?

5. 4. In package reshape2 the opposite of melt is cast. – Andrie.

How do I Unmelt a data frame in R?

We can use pivot() function to unmelt a DataFrame object and get the original dataframe. The pivot() function 'index' parameter value should be same as the 'id_vars' value. The 'columns' value should be passed as the name of the 'variable' column. The unmelted DataFrame values are the same as the original DataFrame.

What is reshape2?

Reshape2 is a package that allows us to easily transform our data into whatever structure we may need. Many of us are used to seeing our data structured so that corresponds to a single participant and each column corresponds to a variable. This type of data structure is known as wide format.

What package is melt in R?

The reshape2 package for R provides useful functionality to avoid having to hack data around in a spreadsheet prior to import into R. The melt function takes data in wide format and stacks a set of columns into a single column of data.


1 Answers

How could R know the ordering that existed before the melt? i.e. the notion that row one of x matches up with row one of y.

If you add an index column (since R will complain about duplicated row.names) you can do this operation simply:

dfr$idx <- seq_along(dfr$x)   
mlt <- melt(dfr, id.var='idx')
dcast(mlt, idx ~ variable, value.var='value')
like image 98
Justin Avatar answered Sep 20 '22 22:09

Justin