Search code examples
rlistr-factor

modify name and number of levels for factors within a list


I wonder how to rename and change the number levels of factors within a list.

I have something like this;

A <- factor(sample(letters,size=10,replace=TRUE))
B <- factor(sample(letters,size=10,replace=TRUE))
C <- factor(sample(letters,size=10,replace=TRUE))

l <- list(A,B,C)

names(l) <- c('A','B','C')

And I would for example like to change the number of the levels to equal only 1 and the name to e.g. a, b, c respectively for the different factors. The output would be something like this

$A
[1] a a a a a a a a a a
Levels: a

$B
[1] b b b b b b b b b b
Levels: b

$C
[1] c c c c c c c c c c
Levels: c 

Any pointers would be highly appreciated, thanks!


Solution

  • You could use mapply for this:

    new.levels <- c('a', 'b', 'c')
    replace.fun <- function(f, nl) `levels<-`(f, rep(nl, length(f)))
    mapply(replace.fun, l, new.levels, SIMPLIFY=FALSE)
    $A
     [1] a a a a a a a a a a
    Levels: a
    
    $B
     [1] b b b b b b b b b b
    Levels: b
    
    $C
     [1] c c c c c c c c c c
    Levels: c