替换NA值 [英] replacing NA values
本文介绍了替换NA值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个具有三个值的变量,NA,是,MayBe.
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"
我正在尝试将NA值替换为否,所以我使用此代码
I am trying to replace the NA values with No so I use this code
Data1$Col1[is.na(Data1$Col1)]= "No"
我遇到错误
In `[<-.factor`(`*tmp*`, is.na(Data1$Col1), value = c(NA, :
invalid factor level, NA generated
我写了一个ifelse语句来替换NA,
I wrote an ifelse statement to replace the NA,
Data1$Col1=ifelse(is.na(Data1$Col1_ == 'TRUE'), "No",Data1$Col1)
这可行,但是我正在寻找一些有效的方法来替换NA.
and this works but I am looking for some efficient ways to do replace the NAs.
推荐答案
您可以使用addNA()
和levels<-
替换功能.
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
这篇关于替换NA值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文