Replace in a factor column

后端 未结 6 1731
南方客
南方客 2020-12-03 02:43

I want to replace values in a factors column with a valid value. But I can not find a way. This example is only for demonstration. The original data

6条回答
  •  心在旅途
    2020-12-03 03:31

    I had similar issues and I want to add what I consider the most pragmatic (and also tidy) solution:

    Convert the column to a character column, use mutate and a simple ifelse-statement to change the NA values to what you want the factor level to be (I have chosen "None"), convert it back to a factor column:

    df %>% mutate(
    a = as.character(a),
    a = ifelse(is.na(a), "None", a),
    a = as.factor(a)
    )
    

    Clean and painless because you do not actually have to dabble with NA values when they occur in a factor column. You bypass the weirdness and end up with a clean factor variable.

提交回复
热议问题