R : Convert Data from Wide to Long Format

Live Online Training : Data Science with R

- Explain Advanced Algorithms in Simple English
- Live Projects
- Case Studies
- Job Placement Assistance
- Get 10% off till Oct 26, 2017
- Batch starts from October 28, 2017

This tutorial explains how to convert data from wide to long format with R programming.
R Code : Convert Data from Wide to Long
Note : Before running the code below, Install reshape2 package if not installed already.

R Code

The following program would create a sample data for demonstration.
df = read.table(text= "ID Product1 Product2 Product3 Product4
1 1 NA 1 1
2 1 1 NA 1
3 1 1 NA NA
4 1 1 1 1", header=TRUE)
The following code would turn our data from wide to long format.
library(reshape2)
x = colnames(df[,-1])
t2 <- melt(df,id.vars = "ID",measure.vars = x , variable.name="Product", value.name="value",na.rm = TRUE)
t2 = t2[order(t2$ID),]

Explanation :

  1. id.vars - additional variables to keep in the output.
  2. measure.vars - variables to be reshaped
  3. variable.name - name of variable used to store measured variable names
  4. value.name - name of variable used to store values


Note : If you do not want to remove NA values, make na.rm = TRUE to na.rm = FALSE.

Tutorial : Convert data from long to wide format

R Tutorials : 75 Free R Tutorials

About Author:

Deepanshu founded ListenData with a simple objective - Make analytics easy to understand and follow. He has close to 7 years of experience in data science and predictive modeling. During his tenure, he has worked with global clients in various domains like retail and commercial banking, Telecom, HR and Automotive.


While I love having friends who agree, I only learn from those who don't.

Let's Get Connected: Email | LinkedIn

Get Free Email Updates :
*Please confirm your email address by clicking on the link sent to your Email*

Related Posts:

1 Response to "R : Convert Data from Wide to Long Format"

  1. I would use tidyr for a nice clean data conversion

    ReplyDelete

Next → ← Prev