融化数据框,重塑高大的数据框架

Anu*_*hit 4 r dataframe melt

我有以下数据框(df),尽管我认为我无法解决如何执行以下操作:

输入:

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
Run Code Online (Sandbox Code Playgroud)

预期产出:

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
Run Code Online (Sandbox Code Playgroud)

tal*_*lat 5

这是一个tidyr选项:

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 
Run Code Online (Sandbox Code Playgroud)

如果您的列存储为因子,则会发出警告,但您可以忽略它.

你可以做同样的reshape2,data.table,reshape从基础R(统计数据),可能有一些其他的库.