0

I have a list of factors and each factor may has some NA. Now I want to add a level for NA and rename it as Missing. I also what to make sure that Missing is the last one in each level. Here is my code but it doesn't work.

data = list(a = factor(c(1,1,2,2,3,NA,NA)), 
            b = factor(c("a","b","b")), 
            c = factor(c(3,4,NA,3)))
data = lapply(data, FUN = function(x) {
    if (any(is.na(x))) {
        x = addNA(x)
        levels(x)[length(levels(x))] = "Missing"
    }
})

Any help would be appreciated.

mutian
  • 77
  • 1
  • 7
  • See [this post](https://stackoverflow.com/questions/27195956/convert-na-into-a-factor-level) and [this post](https://stackoverflow.com/questions/45216532/how-can-i-keep-na-when-i-change-levels). – lmo Aug 10 '17 at 15:12

1 Answers1

2

We can try

lapply(data, function(x) {
     if(anyNA(x)) {
     levels(x) <- c(levels(x), "Missing")
     x[is.na(x)] <- "Missing"
     x}
     else x

  })
#$a
#[1] 1       1       2       2       3       Missing Missing
#Levels: 1 2 3 Missing

#$b
#[1] a b b
#Levels: a b

#$c
#[1] 3       4       Missing 3      
#Levels: 3 4 Missing
akrun
  • 874,273
  • 37
  • 540
  • 662