R Programming: replace missing values in column of a data frame [duplicate]

StackOverflow https://stackoverflow.com/questions/23409388

  •  13-07-2023
  •  | 
  •  

Вопрос

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!

Это было полезно?

Решение

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)

Другие советы

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

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

should add it.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top