2016-01-19 134 views
4

我有以下的数据帧(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 

预期输出:

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 
+0

你指的是第一部分是数据帧,但DATE1,DATE2,DATE3是 '字符' 列? – Gopala

+4

返回给发件人。是我会做的。所有最后三列需要被业务ID – rawr

回答

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 

如果您的列存储为因素,但您可以忽略该列,则会发生此警告。

您可以使用reshape2data.table,reshape从基本R(统计信息)和可能的其他库中执行相同的操作。

+1

调换,如果您将结果输入到'dplyr :: select',则可以删除创建的附加日期列。 '%>%dplyr :: select(-date)'。道歉docendo,并不意味着要窃取你的答案,没有意图的罪行,回答删除。 – jamieRowen

3
library(reshape2) 
df.m<-melt(x,id.var=c("id", "business_id","type")) 
dcast(df.m,id+business_id+variable~type) 

如果你愿意,你可以摆脱变量“变量”。

id business_id variable Month MonthendBankBalance TotalNetDeposits 
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 
+1

什么是'库(plyr)'在这里做?另外,你可以使用'dcast(熔化(df,id.var = 1:3),...〜类型)' –

+0

以某种方式使它成为单线,我认为'dcast'来自'plyr'。感谢收获。好的一个班轮.. – Ananta

+1

你可以将其添加到答案。它也将更好地移除'库(plyr)',现在我们在同一页面上。之后我答应(+1)。 –

4

我们可以使用base R

cbind(df1[1:2],setNames(as.data.frame(t(df1[-(1:3)])), df1$type)) 
#  id business_id Month Total Net Deposits Month end Bank Balance 
#date1 1   A1 13/10/13    1500     729 
#date2 1   A1 13/09/13    951     650 
#date3 1   A1 13/08/13    190     164