Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Melt the data frame, reshape a tall data frame

Tags:

dataframe

r

melt

I have the following data frame (df) and as much as I can think I am unable to wrap my head around how to do the following:

Input:

id  business_id type                      date1     date2     date3
1   A1          Month                     13/10/13  13/09/13  13/08/13
1   A1          Total Net Deposits        1500      951       190
1   A1          Month end Bank Balance    729       650       164

Expected Output:

id  business_id Month       Total Net Deposits  Month end Bank Balance 
1   A1          13/10/13    1500                729 
1   A1          13/09/13    951                 650
1   A1          13/09/13    190                 164
like image 214
Anubhav Dikshit Avatar asked Dec 15 '22 09:12

Anubhav Dikshit


1 Answers

Here's a tidyr option:

library(tidyr)
df %>% 
  gather(date, val, date1:date3) %>% 
  spread(key = type, val = val)
#  id business_id  date    Month Month end Bank Balance Total Net Deposits
#1  1          A1 date1 13/10/13                    729               1500
#2  1          A1 date2 13/09/13                    650                951
#3  1          A1 date3 13/08/13                    164                190
#Warning:
#attributes are not identical across measure variables; they will be dropped 

The warning occurs if your columns are stored as factors but you can ignore that.

You can do the same with reshape2, data.table, reshape from base R (stats) and probably some other libraries.

like image 60
talat Avatar answered Jan 04 '23 10:01

talat