【R语言 算法设计】信用贷款余额计算

#date:2016-02-24
#####设置
rm(list = ls())
options(scipen =20)

########################step0:读取数据##########################
data<-read.table("E:\\贷款余额\\信用贷款.txt",sep="\t",header=T)
#########################step1:数据处理#########################
library(lubridate)
library(plyr)
library(reshape)
library(data.table)
####变形
data101<-melt(data,id=c("owner_user_id","y","m","d","in_out_type"))
data101<-cast(data101,owner_user_id+y+m+d~in_out_type,sum)
####in-out
data101$in_out<-data101[,5]-data101[,6]
####分组累加求和
data101<-data.table(data101)
data102<-data101[,cumsum(in_out),by=owner_user_id]
data103<-cbind(data101,data102)
data104<-as.data.frame(data103)
data104<-data104[,c(1:4,9)]
data104<-arrange(data104,owner_user_id,y,m,-d)
####分组求最小值并判断最小值是否小于0,小于0取绝对值,大于0让最小值等于0
data104_min<-ddply(data104,.(owner_user_id),summarize,V1_min=min(V1))
data104_min$flag<-0
for(i in 1:nrow(data104_min)){
if(data104_min[i,2]>0){
data104_min[i,3]<-0
}else{data104_min[i,3]<-abs(round(data104_min[i,2],2))
}
}
data104_min<-data104_min[,c(1,3)]
#######如果最小值小于0则加回分组累加求和的值
data104<-merge(data104,data104_min)
data104$finally<-round(data104[,5]+data104[,6],2)
######分组取第一个
data105<-ddply(data104,.(owner_user_id,y,m),summarize,balance=head(finally,1))
data105_output<-write.table(data105,"E:\\贷款余额\\data105_balance.txt",row.names=F,sep="\t")
View(data105)
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页