简体   繁体   中英

R changing NA to a level in a vector

I have a vector of a data frame that contains about 150000 rows.

The values of that vector are either “M” or “F” or NA.

So when I ask for levels, I got this:

Levels(cards$MaritialStatus)
[1] "M" "S"

My Purpose

I want to scale (normalize) that vector. Thus, I need to change the NA values to “unknown” word, then I can do the normalization myself.

What I did is:

cards$MaritalStatus[is.na(x = cards$MaritalStatus)] <- "unknown"

What I got is:

Warning message:
In `[<-.factor`(`*tmp*`, is.na(x = cards$MaritalStatus), value = c(1L,  :
  invalid factor level, NA generated

However, nothing has changed in my data frame, I can still see the NA values, and when I ask for the levels of that vector, I am still getting just “M” and “S”.

What did I forget please?

Try this:

levels(cards$MaritalStatus)<-c(levels(cards$MaritalStatus),"unknown")
cards$MaritalStatus[is.na(cards$MaritalStatus)] <- "unknown"

Try this solution:

cards <- data.frame(MaritalStatus=c("M","M","S","S",NA,"M","M",NA,"S","S"))

cards$MaritalStatus <- addNA(cards$MaritalStatus)
levels(cards$MaritalStatus)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM