The goal of this tutorial is to transform a melted table into the original dataframe again
# First we load the libraries
library(reshape2)
library(dplyr)
# In this tutorial we are going to use the iris dataset
data("iris")
# We are going to calculate the average of every feature
iris_gr <- iris %>% group_by(Species) %>% summarise_all(mean) %>% as.data.frame()
iris_gr
## Species Sepal.Length Sepal.Width Petal.Length Petal.Width
## 1 setosa 5.006 3.428 1.462 0.246
## 2 versicolor 5.936 2.770 4.260 1.326
## 3 virginica 6.588 2.974 5.552 2.026
# We use melt to create a melted table
iris_melted <- melt(iris_gr)
## Using Species as id variables
iris_melted
## Species variable value
## 1 setosa Sepal.Length 5.006
## 2 versicolor Sepal.Length 5.936
## 3 virginica Sepal.Length 6.588
## 4 setosa Sepal.Width 3.428
## 5 versicolor Sepal.Width 2.770
## 6 virginica Sepal.Width 2.974
## 7 setosa Petal.Length 1.462
## 8 versicolor Petal.Length 4.260
## 9 virginica Petal.Length 5.552
## 10 setosa Petal.Width 0.246
## 11 versicolor Petal.Width 1.326
## 12 virginica Petal.Width 2.026
# We will use the dcast function from reshape2 to unmelt the table
dcast(iris_melted, Species ~ variable)
## Species Sepal.Length Sepal.Width Petal.Length Petal.Width
## 1 setosa 5.006 3.428 1.462 0.246
## 2 versicolor 5.936 2.770 4.260 1.326
## 3 virginica 6.588 2.974 5.552 2.026
# We can also create the transposed dataframe changing the order in the dcast function
dcast(iris_melted, variable ~ Species)
## variable setosa versicolor virginica
## 1 Sepal.Length 5.006 5.936 6.588
## 2 Sepal.Width 3.428 2.770 2.974
## 3 Petal.Length 1.462 4.260 5.552
## 4 Petal.Width 0.246 1.326 2.026
In this tutorial we have learnt how to unmelt a melted dataframe.