celestialgod

Transform to WOE

Feb 4th, 2016
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 1.01 KB | None | 0 0
  1. library(data.table)
  2. library(magrittr)
  3. library(plyr)
  4. library(dplyr)
  5. library(Information)
  6.  
  7. dt <- data.table:::data.table(response = rbinom(100, 1, 0.35), x1 = rnorm(100),
  8.                  x2 = sample(LETTERS[1:3], 100, TRUE))
  9. IV <- Information:::create_infotables(dt, y = "response")
  10. closeAllConnections()
  11. new_dt <- names(IV$Tables) %>% plyr:::llply(function(varName){
  12.   if (grepl("\\[[^]]*\\]", IV$Tables[[varName]][[varName]][1]))
  13.   {
  14.     boundaries <- IV$Tables[[varName]][[varName]] %>% gsub("\\[|\\]", "", .) %>%
  15.       strsplit(',') %>% do.call(rbind, .) %>% {c(.[,1], .[nrow(.),2])} %>% as.numeric
  16.     cut(floor(dt[[varName]]*100)/100, boundaries, include.lowest = TRUE) %>%
  17.       {IV$Tables[[varName]][["WOE"]][as.integer(.)]} %>% return
  18.  
  19.   } else
  20.   {
  21.     plyr:::mapvalues(dt[[varName]], IV$Tables[[varName]][[varName]],
  22.                      IV$Tables[[varName]][["WOE"]]) %>% as.numeric %>% return
  23.   }
  24. }) %>% set_names(names(IV$Tables)) %>% dplyr:::as_data_frame %>%
  25.   mutate(response = dt$response)
Advertisement
Add Comment
Please, Sign In to add comment