Replace in a factor column

后端 未结 6 1725
南方客
南方客 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条回答
  •  -上瘾入骨i
    2020-12-03 03:31

    The problem is that NA is not a level of that factor:

    > levels(df$a)
    [1] "2"  "4"  "5"  "9"  "10"
    

    You can't change it straight away, but the following will do the trick:

    df$a <- as.numeric(as.character(df$a))
    df[is.na(df$a),1] <- 88
    df$a <- as.factor(df$a)
    > df$a
     [1] 9  88 3  9  5  9  88 8  3  9 
    Levels: 3 5 8 9 88
    > levels(df$a)
    [1] "3"  "5"  "8"  "9"  "88"
    

提交回复
热议问题