替换 NA 值

replacing NA values

我有一个具有三个值的变量,NA、Yes、MayBe。

当我在该变量上使用级别和 class 函数时,我得到了这些值

          > levels(Data1$Case)
          "Yes"                 "May Be"

          > class(Data1$Case)
          "factor"

我正在尝试用 No 替换 NA 值,所以我使用此代码

     Data1$Col1[is.na(Data1$Col1)]= "No"

我收到一个错误,

       In `[<-.factor`(`*tmp*`, is.na(Data1$Col1), value = c(NA,  :
       invalid factor level, NA generated

我写了一个ifelse语句来代替NA,

      Data1$Col1=ifelse(is.na(Data1$Col1_ == 'TRUE'), "No",Data1$Col1)

这可行,但我正在寻找一些有效的方法来替换 NA。

您可以使用 addNA()levels<- 替换功能。

x <- factor(c(NA, "Yes", "Maybe"))
# [1] <NA>  Yes   Maybe
# Levels: Maybe Yes

## If present, add NA to the factor levels
addNA(x)
# [1] <NA>  Yes   Maybe
# Levels: Maybe Yes <NA>
y <- addNA(x)

## replace the NA level with 'No'
levels(y)[is.na(levels(y))] <- "No"
y
# [1] No    Yes   Maybe
# Levels: Maybe Yes No