stack and unstack function in R

Stack and unstack function in R are two important functions.

  •  Stack function in R stacks a data set i.e. it converts a data set from unstacked form to stacked form.
  • Unstack function in R unstacks a data set i.e. it converts the data set from stacked form to unstacked form.

Syntax for stack and unstack function in R:

  1. stack(dataframe)
  2. unstack(dataframe)

Example of unstack function in R:

Lets use the “PlantGrowth” data set to demonstrate unstack function in R. PlantGrowth data set is shown below.

 valuesind
14.17ctrl
25.58ctrl
35.18ctrl
46.11ctrl
54.5ctrl
64.61ctrl
75.17ctrl
84.53ctrl
95.33ctrl
105.14ctrl
114.81trt1
124.17trt1
134.41trt1
143.59trt1
155.87trt1
163.83trt1
176.03trt1
184.89trt1
194.32trt1
204.69trt1
216.31trt2
225.12trt2
235.54trt2
245.5trt2
255.37trt2
265.29trt2
274.92trt2
286.15trt2
295.8trt2
305.26trt2
# unstack function in R

df<-PlantGrowth
unstacked_df<-unstack(df)
Unstacked_df

In the above example unstack() function in R converts the data from stacked form to unstacked form. So the output will be

     ctrl      trt1      trt2

1  4.17     4.81    6.31

2  5.58     4.17    5.12

3  5.18     4.41    5.54

4  6.11     3.59    5.50

5  4.50     5.87    5.37

6  4.61     3.83    5.29

7  5.17     6.03    4.92

8  4.53     4.89    6.15

9  5.33     4.32    5.80

10 5.14    4.69    5.26

Example of stack function in R:

Lets use the above data frame to demonstrate stack() function in R.

 # stack function in R

 stacked_df<-stack(Unstacked_df)
 stacked_df

the above code stacks the data frame back to original data frame, so the output will be

      values    ind

1     4.17      ctrl

2     5.58      ctrl

3     5.18      ctrl

4     6.11      ctrl

5     4.50      ctrl

6     4.61      ctrl

7     5.17      ctrl

8     4.53      ctrl

9     5.33      ctrl

10    5.14     ctrl

11    4.81     trt1

12    4.17      trt1

13    4.41      trt1

14    3.59      trt1

15    5.87      trt1

16    3.83      trt1

17    6.03      trt1

18    4.89      trt1

19    4.32      trt1

20    4.69      trt1

21    6.31      trt2

22    5.12      trt2

23    5.54      trt2

24    5.50      trt2

25    5.37      trt2

26    5.29      trt2

27    4.92      trt2

28    6.15      trt2

29    5.80      trt2

30    5.26      trt2

previous small stack and unstack function in r                                                                                                                next small stack and unstack function in r