Search code examples
rif-statementaggregater-factor

R: "Binning" categorical variables


I have a data.frame which has 13 columns with factors. One of the columns contains credit rating data and has 54 different values:

levels(TR_factor$crclscod)
[1] "A"  "A2" "AA" "B"  "B2" "BA" "C"  "C2" "C5" "CA" "CC" "CY" "D" 
[14] "D2" "D4" "D5" "DA" "E"  "E2" "E4" "EA" "EC" "EF" "EM" "G"  "GA"
[27] "GY" "H"  "I"  "IF" "J"  "JF" "K"  "L"  "M"  "O"  "P1" "TP" "U" 
[40] "U1" "V"  "V1" "W"  "Y"  "Z"  "Z1" "Z2" "Z4" "Z5" "ZA" "ZY" 

What I want is to "bin" those categories into something like

levels(TR_factor$crclscod)
[1] "all A"  "all B"   "all C"  "all D" [...] "all z"

My attempt was to use some form of a construct like this

crcls_reduced <- ifelse(TR_factor$crclscod %in% c("A","A2", "AA", "B", "B2","BA", "C" , "C2" ,"C5" ,"CA" ,"CC", "CY", "D",  "D2", "D4", "D5" ,"DA", "E" , "E2", "E4" ,"EA", "EC" ,"EF", "EM", "G" , "GA",  "GY" ,"H", "I",  "IF" ,"J" , "JF" ,"K", "L", "M", "O", "P1","TP", "U", "U1" ,"V",  "V1", "W" , "Y" , "Z" , "Z1", "Z2", "Z4" ,"Z5", "ZA", "ZY"), "A", "B", "C", "D", "E", "G", "H", "I", "J", "K", "L", "M", "O", "P", "T", "U", "V", "W", "Y", "Z")

but of course, this construct only is able to produce a binary output. Of course I can do the whole thing manually for each letter, but I hoped that stackoverflow knows a faster and more efficient way -- for instance using some package that I am unaware of.


Solution

  • You could try

     factor(paste('all', sub('(.).*$', '\\1', v1)))
    

    Or

     factor(paste('all', substr(v1, 1,1)))
    

    data

    v1 <- c("A", "A2", "AA", "B", "B2", "BA", "C", "C2", "C5", "CA", "CC", 
    "CY", "D", "D2", "D4", "D5", "DA", "E", "E2", "E4", "EA", "EC", 
    "EF", "EM", "G", "GA", "GY", "H", "I", "IF", "J", "JF", "K", 
    "L", "M", "O", "P1", "TP", "U", "U1", "V", "V1", "W", "Y", "Z", 
    "Z1", "Z2", "Z4", "Z5", "ZA", "ZY")