问题
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