replacing NA values

♀尐吖头ヾ 提交于 2020-01-03 04:35:13

问题


I have a variable that has three values, NA, Yes, MayBe.

When I use levels and class function on that variable I get theses values

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

          > class(Data1$Case)
          "factor"

I am trying to replace the NA values with No so I use this code

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

I am getting an error,

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

I wrote an ifelse statement to replace the NA,

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

and this works but I am looking for some efficient ways to do replace the NAs.


回答1:


You can use addNA() and the levels<- replacement function.

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


来源:https://stackoverflow.com/questions/29572350/replacing-na-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!