How to Stack DataFrame Columns in R? - GeeksforGeeks (2024)

A dataframe is a tubular structure composed of rows and columns. The dataframe columns can be stacked together to divide the columns depending on the values contained within them.

Method 1: Using stack method

The cbind() operation is used to stack the columns of the data frame together. Initially, the first two columns of the data frame are combined together using the df[1:2]. This is followed by the application of stack() method applied on the last two columns.

The stack method in base R is used to transform data available in the form of separate columns within a data frame or a list into a single column. The stack method produces a result in the form of a data frame with two columns:

  • values: the result produced by concatenating the selected vectors in x.
  • ind: a factor indicating from which vector in x the observation originated.

Syntax:

stack(x)

Arguments :

  • x – a list or data frame to be stacked

Original Data frame looks as:

 col1 semester quiz_sst quiz_maths1 Yash A 1 22 Yash B 3 43 Mallika A 4 64 Mallika B 8 25 Muskan A 9 76 Muskan B 1 3

R

# creating a data frame

data <- data.frame(col1=c('Yash', 'Yash', 'Mallika',

'Mallika', 'Muskan', 'Muskan'),

semester=c(rep(LETTERS[1:2],3)),

quiz_sst=c(1, 3, 4, 8, 9, 1),

quiz_maths=c(2, 4, 6, 2, 7, 3))

# binding the first two columns as it is

# and stacking the third and fourth columns

data_mod <- cbind(data[1:2], stack(data[3:4]))

print(data_mod)

Output

 col1 semester values ind1 Yash A 1 quiz_sst2 Yash B 3 quiz_sst3 Mallika A 4 quiz_sst4 Mallika B 8 quiz_sst5 Muskan A 9 quiz_sst6 Muskan B 1 quiz_sst7 Yash A 2 quiz_maths8 Yash B 4 quiz_maths9 Mallika A 6 quiz_maths10 Mallika B 2 quiz_maths11 Muskan A 7 quiz_maths12 Muskan B 3 quiz_maths

Method 2: Using melt method

The reshape2 package in R can be used to change the structure of the data supplied and can be installed and imported into the working space using the following command :

install.packages("reshape2")library(reshape2)

The melt method in this package can be used to stack data frame columns together. It is used to reshape and elongate the data frame. The melt() method has the following syntax :

melt(data, id.var , variable.name)

Arguments :

  • data – The data frame to stack columns of
  • id.ar – The columns to use as primary key
  • variable.name – The new column name to append

Original Data Frame looks as:

 col1 semester quiz_sst quiz_maths1 Yash A 1 22 Yash B 3 43 Mallika A 4 64 Mallika B 8 25 Muskan A 9 76 Muskan B 1 3

R

# importing the required library

library("reshape2")

# creating a data frame

data <- data.frame(col1=c('Yash', 'Yash', 'Mallika',

'Mallika', 'Muskan', 'Muskan'),

semester=c(rep(LETTERS[1:2],3)),

quiz_sst=c(1, 3, 4, 8, 9, 1),

quiz_maths=c(2, 4, 6, 2, 7, 3))

# binding the first two columns as it is

# and stacking the third and fourth columns

data_mod <- reshape2::melt(data, id.var = c('col1', 'semester'),

variable.name = 'quiz_marks')

print(data_mod)

Output

[1] "Modified DataFrame" col1 semester quiz_marks value1 Yash A quiz_sst 12 Yash B quiz_sst 33 Mallika A quiz_sst 44 Mallika B quiz_sst 85 Muskan A quiz_sst 96 Muskan B quiz_sst 17 Yash A quiz_maths 28 Yash B quiz_maths 49 Mallika A quiz_maths 610 Mallika B quiz_maths 211 Muskan A quiz_maths 712 Muskan B quiz_maths 3

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!


Last Updated : 19 Dec, 2021

Like Article

Save Article

As an expert in data manipulation and R programming, I've extensively worked with data frames, utilizing various techniques to transform and reshape data. My hands-on experience allows me to provide insights into the concepts discussed in the provided article.

The article discusses two methods for stacking columns in a data frame: using the stack method (Method 1) and the melt method from the reshape2 package (Method 2). Let's break down the key concepts and explain the processes involved in each method:

Method 1: Using stack method

1. DataFrame Structure:

  • A DataFrame is a tabular structure composed of rows and columns.

2. Stacking Columns using cbind and stack:

  • cbind() operation is used to combine columns.
  • stack() method in base R transforms separate columns into a single column.
  • The result is a new DataFrame with two columns: 'values' and 'ind'.

3. Syntax of stack:

  • stack(x) where x is a list or data frame to be stacked.

4. Example:

  • Original DataFrame:
     col1 semester quiz_sst quiz_maths
     Yash   A       1        2
     Yash   B       3        4
     ...
  • Stacked DataFrame:
     col1 semester values ind
     Yash   A        1  quiz_sst
     Yash   B        3  quiz_sst
     ...

5. Implementation:

   data_mod <- cbind(data[1:2], stack(data[3:4]))

Method 2: Using melt method (reshape2 package)

1. Installing and Importing reshape2 Package:

  • The reshape2 package is used for data reshaping.
  • It can be installed with install.packages("reshape2") and imported with library(reshape2).

2. Stacking Columns using melt:

  • The melt method reshapes and elongates the data frame.
  • Arguments include the data frame (data), id variables (id.var), and the new column name (variable.name).

3. Syntax of melt:

  • melt(data, id.var, variable.name)

4. Example:

  • Original DataFrame: Same as in Method 1.
  • Melted DataFrame:
     col1 semester quiz_marks value
     Yash   A      quiz_sst    1
     Yash   B      quiz_sst    3
     ...

5. Implementation:

   data_mod <- reshape2::melt(data, id.var = c('col1', 'semester'), variable.name = 'quiz_marks')

These methods are powerful tools for reshaping data frames, and mastering them is essential for efficient data manipulation in R. Whether you're a data scientist, analyst, or programmer, these techniques will enhance your ability to work with diverse datasets.

How to Stack DataFrame Columns in R? - GeeksforGeeks (2024)
Top Articles
Latest Posts
Article information

Author: Gregorio Kreiger

Last Updated:

Views: 6105

Rating: 4.7 / 5 (77 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Gregorio Kreiger

Birthday: 1994-12-18

Address: 89212 Tracey Ramp, Sunside, MT 08453-0951

Phone: +9014805370218

Job: Customer Designer

Hobby: Mountain biking, Orienteering, Hiking, Sewing, Backpacking, Mushroom hunting, Backpacking

Introduction: My name is Gregorio Kreiger, I am a tender, brainy, enthusiastic, combative, agreeable, gentle, gentle person who loves writing and wants to share my knowledge and understanding with you.