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?
5. 4. In package reshape2 the opposite of melt is cast. – Andrie.
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.
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.
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.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With