问题
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.
回答1:
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")
回答2:
This seems similar to @akrun's answer and also uses the fact that the first letter is the desired new level:
myf <- as.factor(paste(LETTERS, 1:100, sep=''))
myf_binned <- myf
levels(myf_binned) <- sapply(levels(myf_binned),
function(l) substring(l, 1, 1))
myf_binned
You can then see 'bin' membership by
table(as.character(myf_binned))
# A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
# 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 3 3 3 3
Edit:
Actually, substring
takes vectors, so it can be even simpler
levels(myf_binned) <- substring(levels(myf_binned), 1, 1)
来源:https://stackoverflow.com/questions/28968983/r-binning-categorical-variables