在 R 中重塑数据框
Posted
技术标签:
【中文标题】在 R 中重塑数据框【英文标题】:Reshaping an data frame in R 【发布时间】:2015-12-10 01:48:10 【问题描述】:我在 R 中有这个长格式的数据框,看起来像这样..
Branch.Name Customer.ID Loan.Type Date Stage Time
A C001 Home 20/11/05 Processing 10
A C001 Home 20/11/05 Approval 30
A C001 Home 20/11/05 Finalize 5
A C002 Business 23/11/05 Processing 30
我想把它转换成宽格式..
Branch.Name Customer.ID Loan.Type Date Processing Approval Finalize
A C001 Home 20/11/05 10 30 5
B C002 Business 20/11/05 30 10 0
B C003 Business 20/11/05 12 15 0
我看着重塑和融化,但我得到了混乱的答案......
提前致谢
P.S:并非所有行都有“Processing”、“Approval”和“Finalize”作为阶段,有些可能有额外的阶段
【问题讨论】:
我认为您输入数据中的Branch.Name
应该有B'. Perhaps
library(reshape2);dcast(df1, ...~Stage, value.var='Time', fill=0) `
【参考方案1】:
这是一个基本的从长到宽的转换。
尝试以下方法之一:
## Base R
reshape(mydf, direction = "wide",
idvar = c("Branch.Name", "Customer.ID", "Loan.Type", "Date"),
timevar = "Stage")
## reshape2
library(reshape2)
dcast(mydf, Branch.Name + Customer.ID + Loan.Type + Date ~ Stage, value.var = "Time")
## dcast(mydf, ... ~ Stage, value.var = "Time")
## tidyr
library(tidyr)
spread(mydf, Stage, Time)
【讨论】:
以上是关于在 R 中重塑数据框的主要内容,如果未能解决你的问题,请参考以下文章