How to Stack Columns in R

05.09.2021

Intro

Stacking allows you to combine multiple vectors into a single vector and specify the origination factor. Our example in a second will make this clear. We can stack vectors using the stack function. There is also the unstack function which will reverse the operation. In this article, we will learn how to stack columns in R.

Using the Stack Function

Let’s take a look at the following data frame that shows the character and their homeworld. Notice that each column represents the homeworld.

df = data.frame(
  Tatooine = c("Luke Skywalker", "Anakin Skywalker"),
  Naboo = c("R2-D2", "Palpatine")
)
df
# Tatooine          Naboo
# Luke Skywalker      R2-D2         
# Anakin Skywalker  Palpatine

We can use the stack method to pivot the table where all of the planet names are in a single column. This would be helpful as the format is more similar to what we expect in data analysis.

new.df = stack(df)
new.df
##             values      ind
## 1   Luke Skywalker Tatooine
## 2 Anakin Skywalker Tatooine
## 3            R2-D2    Naboo
## 4        Palpatine    Naboo

We can then rename the columns to make the data frame more clear.

names(new.df) = c("name", "homeworld")
new.df
##               name homeworld
## 1   Luke Skywalker  Tatooine
## 2 Anakin Skywalker  Tatooine
## 3            R2-D2     Naboo
## 4        Palpatine     Naboo

We can also reverse the procedure using the unstack method.

unstack(as.data.frame(new.df))
##           Tatooine     Naboo
## 1   Luke Skywalker     R2-D2
## 2 Anakin Skywalker Palpatine