Karl Sahyoun February 2016

Replace NA values by string "Unknown" in R

I have a list X that contains the 12 months in a year. In my data, I have a column Y that has the following levels: "Done", "Not Done" and "". I want to replace the "" by the string "Unknown".

I tried:

for (i in 1:length(X)) {
   X[[i]]$Y[which(is.na(X[[i]]$Y))] == "Unknown"
}

I get the error:

"Error: unexpected input in " PList15[[i]]$IB.Opportunity.Type[which(is.na(PList15[[i]]$IB.Opportunity))] == "Unknown"

Answers


DatamineR February 2016

You don't need a loop for this, you can do it like:

# Some data with `""`
v <- 1:10
v[c(3,5,8)] <- ""
v
 [1] "1"  "2"  ""   "4"  ""   "6"  "7"  ""   "9"  "10"


v[v == ""] <- "Unknown"

 [1] "1"       "2"       "Unknown" "4"       "Unknown" "6"       "7"       "Unknown" "9"       "10"


HubertL February 2016

Since Y is a factor, you could do:

levels(X$Y)[levels(X$Y)==""] <- "unknown"

Post Status

Asked in February 2016
Viewed 3,856 times
Voted 10
Answered 2 times

Search




Leave an answer