What is ‘Stack’ing and ‘Unstack’ing in R


  R Interview Questions

Stacking and unstacking are function that help in reshaping data in R. Data is not always in the format you require. For example, say you have data from 3 temperature sensors in different areas of chicago. And the data you get from these sensors is horizontal.

Even if you wanted to compare the temperatures across sensors, this is not a good format. Instead, if all the temperature data were in a single column, with the second column identifying where the sensor data came from, you can analyze the data much better. This is one of the data reshaping steps.

# Let's take the first 5 rows. 
 > sensors
  sensor_1 sensor_2 sensor_3
1      105       98       90
2      105      113       98
3      102       92      110
4       95      101      103
5       97      113       96

How do we stack these 3 columns into the same column ? Try this

> sensors = stack(sensors)
> sensors
   values      ind
1     105 sensor_1
2     105 sensor_1
3     102 sensor_1
4      95 sensor_1
5      97 sensor_1
6      98 sensor_2
7     113 sensor_2
8      92 sensor_2
9     101 sensor_2
10    113 sensor_2
11     90 sensor_3
12     98 sensor_3
13    110 sensor_3
14    103 sensor_3
15     96 sensor_3

R created a new column automatically, called ind , to indicate which column the row came from. If you did not want to stack all the columns, you can very well specify the columns.

# say you only wanted the first and third sensor's data
> sensors = stack(sensors, select = c("sensor_1","sensor_3"))
> sensors
   values      ind
1     105 sensor_1
2     105 sensor_1
3     102 sensor_1
4      95 sensor_1
5      97 sensor_1
6      90 sensor_3
7      98 sensor_3
8     110 sensor_3
9     103 sensor_3
10     96 sensor_3

Unstacking

Unstacking the data is just as easy. Let’s unstack the dataframe we just stacked.

> sensors = unstack(sensors)
> sensors
  sensor_1 sensor_3
1      105       90
2      105       98
3      102      110
4       95      103
5       97       96

That was easy. Wasn’t it ?

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.