[R] recode letters to numbers

Jim Lemon jim at bitwrit.com.au
Fri Dec 3 22:02:03 CET 2010


On 12/04/2010 01:25 AM, Katharina Noussi wrote:
> Hello,
>
> I have a dataframe assigning various scores on around 20 variables to a list of
> countries. The scores are rated on a scale of (D, C, B, A) and there are also
> some not rated ones (NR) and others are left blank (NA). I now wanted to
> transfer the scores into numeric values (such as NR=0, D=25, C=50, B=27, A=100),
> while also leaving the NA in the dataframe. Can I transform the whole dataframe
> at once or do I need to transform each column separately? How do I correctly
> specify the levels and labels of the new dataframe?
>
Hi Katharina,
Just to muddy the waters a bit further, say your original variable is 
named "score" in a dataframe named "scoredata", and is a factor with the 
usual default alphabetic ordering. Try this:

transform<-c(100,27,50,25,0)
scoredata$newscore<-NA
scoredata$newscore[!is.na(scoredata$score)]<-
  transform[as.numeric(scoredata$score[!is.na(scoredata$score))]

Jim



More information about the R-help mailing list