How can I replace string categories into numbers (such as 'AAA' would become 1, 'AA+' would become 2)?

I found how to create a categorical array from integers but I'm trying to do the opposite as I want to calculate with the ratings.

3 Comments

Although Sean has answered your specific question, needing to convert a categorical to numbers is sometimes an indication that maybe you are trying to do something that could be done another way, or something that categorical isn't really intended for. Can you provide more context?
Sean's answer is exactly what I was looking for. I'm calculating an average rating for a number of bonds. So first I'm retrieving the individual ratings for those bonds (S&P, Moody's, Fitch). After turning them into categorical arrays,
B = categorical(BondRatings);
merging categories
oldcats = {'A-','A- /*+','A- /*-','A- /*'};
B = mergecats(B,oldcats);
and setting the possible categories
catnames = {'AAA','AA+','AA','AA-','A+','A','A-','BBB+','BBB','BBB-','BB+','BB','BB-','B+','B','B-','CCC+','CCC','CCC-','CC','C','D'};
A = setcats(A,catnames);
I need to convert them to numbers to calculate the mean. Afterwards I do exactly the opposite: I transform the means into categories
valueset = [1:22];
Ratings = [double(S_P),double(Moody),double(Fitch)];
FinalRating = categorical(round(nanmean(Ratings,2)),valueset,catnames);

Sign in to comment.

More Answers (0)

Categories

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!