Search code examples
rrecordrattle

R , rattle , recode


R , rattle

here is my data :

KK<- c('yes','no','yes','yes','dp')
LL<- c('dp','no','yes','yes','no')
II<- c('yes','dp','no','no','no')
JJ<- c('yes','no','yes','yes','dp')
AA<- c('no','dp','yes','yes','yes')
MYDATA <- data.frame(KK,LL,II,JJ,AA);MYDATA

Target:

recode 「no」 to 「0.0」

recode 「yes」to 「1.0」

recode 「dp」to 「0.5」

Question: how can i recode in r with the package 「rattle」


Solution

  • We can convert the 'MYDATA' to 'matrix', change the 'character' class to 'factor' by specifying the labels to '0.5, 0, 1' based on the order of levels and assign it back to 'MYDATA'. [] will ensure that the structure remains the same.

    MYDATA[] <- as.numeric(as.character(factor(as.matrix(MYDATA), 
                                labels=c(0.5, 0, 1))))
    
    MYDATA 
    #   KK  LL  II  JJ  AA
    #1 1.0 0.5 1.0 1.0 0.0
    #2 0.0 0.0 0.5 0.0 0.5
    #3 1.0 1.0 0.0 1.0 1.0
    #4 1.0 1.0 0.0 1.0 1.0
    #5 0.5 0.0 0.0 0.5 1.0