1 Goal


The goal of this tutorial is to learn how to melt a table. The process of melting consists of transforming a table with different variables in a table where the columns are melted into variable and value. We can define which columns to use as ids and the rest will be melted.


2 Data import


library(reshape2)

# In this tutorial we are going to use a handmade dataframe
my_dataframe <- data.frame(Person = c("Peter", "Perry"), age = c(33, 37), origin = c("Valencia", "Barcelona"), height = c(178, 183))

my_dataframe
##   Person age    origin height
## 1  Peter  33  Valencia    178
## 2  Perry  37 Barcelona    183

3 Melting the table


# We can use one of the columns as id and we will get as many rows as different columns we had
melt(my_dataframe, id = "Person")
## Warning: attributes are not identical across measure variables; they will
## be dropped
##   Person variable     value
## 1  Peter      age        33
## 2  Perry      age        37
## 3  Peter   origin  Valencia
## 4  Perry   origin Barcelona
## 5  Peter   height       178
## 6  Perry   height       183
# However we could use more columns as id
melt(my_dataframe, id = c("Person", "origin"))
##   Person    origin variable value
## 1  Peter  Valencia      age    33
## 2  Perry Barcelona      age    37
## 3  Peter  Valencia   height   178
## 4  Perry Barcelona   height   183

4 Conclusion


In this tutorial we have learnt how to use one ore more columns to melt the variables of a table. This could be useful when we want to know the weight of a variable compared with the other variables.