stack and unstack function in R are two important functions. Stacking vectors concatenates multiple vectors into a single vector along with a factor indicating where each observation originated using stack() function. Unstacking reverses this operation using unstack() function.
- 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:
stack(dataframe)
unstack(dataframe)
Stack and unstack function in R:
Lets use the “PlantGrowth” data set to demonstrate unstack function in R. PlantGrowth data set is shown below.
Example of unstack function in R:
unstack() function takes up the dataframe as argument and unstacks the dataframe as shown below.
# 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
unstack function in R by subsetting or selecting specific columns
Lets use the “PlantGrowth” data frame to demonstrate unstack() function in R. unstack() function takes up “PlantGrowth” and selects first twenty rows and unstacks them as shown below.
# unstack function in R df<-PlantGrowth unstacked_list = (unstack(df[c(1:20),])) unstacked_list
so the above code unstacks the dataframe and converts them into a list as shown below.
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
Stack function in R by subsetting or selecting specific columns
Lets use the “unstacked_df” data frame to demonstrate stack() function with select argument in R. stack() function takes up “unstacked_df” and selects all the columns except “ctrl” column.
# stack function in R stacked_df1 = stack(unstacked_df, select = -ctrl) stacked_df1
the above code stacks the data frame back to original data frame except “ctrl” column, so the output will be