#' @import data.table
#' @importFrom utils str globalVariables
if(getRversion() >= "2.15.1") utils::globalVariables(c('prev_upb','Prev_Sched_Bal1'))
set_Prev_Sched_Bal1 <- function(Data_P, verbose=FALSE){
stopifnot(is.data.table(Data_P))
# browser()
if(!all(key(Data_P)==c( "LOAN_ID","Monthly.Rpt.Prd"))) {
setkeyv(Data_P, c("LOAN_ID", "Monthly.Rpt.Prd"))
print(key(Data_P))
}
# Data_P[, Count:=1:.N, by="LOAN_ID"]
# Data_P[, last_upb:=ifelse(Count<=7 & is.na(LAST_UPB), ORIG_AMT, LAST_UPB)]
suppressWarnings(Data_P[, c('prev_upb', 'Prev_Sched_Bal1'):=NULL])
Data_P[, prev_upb:=shift(LAST_UPB), by="LOAN_ID"]
# print(key(Data_P))
# Data_P[ MOD_FLAG==shift(MOD_FLAG) & Months.To.Legal.Mat>=0 & shift(Months.To.Legal.Mat)>=0, Prev_Sched_Bal1:=prev_upb *
# ( 1-(1+LAST_RT/1200)^-(Months.To.Legal.Mat)) /
# ( 1-(1+shift(LAST_RT)/1200)^-(shift(Months.To.Legal.Mat))), by="LOAN_ID" ]
Data_P[, # ,
Prev_Sched_Bal1:=fifelse(MOD_FLAG==shift(MOD_FLAG) & Months.To.Legal.Mat>=0 & shift(Months.To.Legal.Mat)>=0, prev_upb *
( 1-(1+LAST_RT/1200)^-(Months.To.Legal.Mat)) /
( 1-(1+shift(LAST_RT)/1200)^-(shift(Months.To.Legal.Mat))), no=NA_real_, na=NA_real_), by="LOAN_ID" ]
loan_ids <- Data_P[is.infinite(Prev_Sched_Bal1), LOAN_ID]
if(verbose) print(loan_ids)
if(length(loan_ids)>0) {
cat("Infitite Scheduled Balance:\n")
print(Data_P[is.infinite( Prev_Sched_Bal1 )])
if(verbose) {
# bad_ids <- Data_P[, any(is.infinite(Data_P$Prev_Sched_Bal1)), by="LOAN_ID"][V1==TRUE]
print( Data_P[loan_ids, .SD[,list(Monthly.Rpt.Prd,shift(last_upb), Months.To.Legal.Mat, shift(Months.To.Legal.Mat), prev_upb *
( 1-(1+LAST_RT/1200)^-(Months.To.Legal.Mat)) /
( 1-(1+shift(LAST_RT)/1200)^-(shift(Months.To.Legal.Mat))))], by="LOAN_ID"])
}
}
invisible(Data_P)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.