Search code examples
rrenamelevelstukey

renaming many levels of a factor - R -


I am trying to rename the names of all the level of my factor variables, so I can run TukeyHSD. Tukey procedure doesn't like when levels are named by numbers. Therefore, I do not care about the name per se, I only want the name to be a character - the names can be single letters from the alphabet.

The problem is that i have very many levels. For example:

x1 <- sample(1:75,100,replace=T) 
x1 <- as.factor(x1)

> str(x1)
 Factor w/ 54 levels "1","2","4","5",..: 26 33 23 23 15 18 21 12 29 16 ...

The only way i know how to rename them all, is by manualy typing the name of each level:

levels(x1) <- c('name1', 'name2',...,'name54')

How can i avoid typying all the names one by one? Is there an automatized renaming?

Thank you!


Solution

  • @Aurèle's answer in the comments might be a solution, but if you don't want any number in your levels, you can try combining random letters. Here is a possible solution:

    sample(combn(letters, 2, FUN = function(x) {paste0(x[1], x[2])}), length(levels(x1)))
    

    Output:

     [1] "uv" "co" "ko" "eg" "ew" "dv" "ej" "px" "bc" "ku" "ip" "hz" "dk" "ou" "cd" "an" "hv" "nz" "uy" "bd"
    [21] "kz" "af" "oy" "qz" "kl" "be" "ox" "bi" "mv" "fo" "el" "gj" "tv" "lv" "cl" "vx" "hl" "hy" "rv" "np"
    [41] "dt" "br" "gz" "av" "aw" "nr" "bj" "ho" "gk" "mq" "ms" "lp" "jw" "gi" "cq"