-2

I am trying to replace all missing value in a column of a data frame. I found the below code:

          df$GROUPE[is.na(df$GROUPE)] <- "OTHER"

However, I am receiving a error message:

       Warning message:
       In `[<-.factor`(`*tmp*`, is.na(df$GROUPE), value = c(NA, 1L, 2L,  :
       invalid factor level, NA generated

Does anybody know how to replace missing values.

Thank you!

user1783504
  • 331
  • 4
  • 7
  • 14

2 Answers2

2

Convert your factor to character then run the previous line again:

df$GROUPE <- as.character(df$GROUPE)

df$GROUPE[is.na(df$GROUPE)] <- "OTHER"

You can refactor the df$GROUPE variable after:

df$GROUPE=as.factor(df$GROUPE)
Thomas
  • 43,637
  • 12
  • 109
  • 140
rmbaughman
  • 921
  • 1
  • 7
  • 17
0

Apparently your GROUPE column is a factor and does not have a level called "OTHER".

levels(f) <- c(levels(f), "OTHER")

should add it.

Thomas
  • 43,637
  • 12
  • 109
  • 140
James King
  • 6,229
  • 3
  • 25
  • 40