why does gsub not replace NA

Viewed 2705

Aim

Replace NA with "Nothing" in character vector

Input

data<-c(NA, NA, "SupineAcid", NA, NA, NA, "UprightAcid", "UprightAcid", 
NA, NA, "UprightAcid", NA, "UprightAcid", NA, NA, "UprightAcid", 
"TotalAcid", NA, NA, NA)

Attempts

gsub(NA,"dd",data)

This leads to all the results being NA

I've also tried with "NA" and fixed=TRUE but the same issue.

3 Answers

In order to change the NA elements in your vector, you can use the is.na function:

data[is.na(data)] = "dd"

 "dd"          "dd"          "SupineAcid"  "dd"          "dd"          "dd"          "UprightAcid"
 "UprightAcid" "dd"          "dd"          "UprightAcid" "dd"          "UprightAcid" "dd"         
 "dd"          "UprightAcid" "TotalAcid"   "dd"          "dd"          "dd"

NA is not the same as "NA". If you make sure that both the first and third arguments use "NA" then it will work.

sub("NA", "dd", paste(data))

Alternately

ifelse(is.na(data), "dd", data)

Another option is replace

replace(data, is.na(data), 'dd')
Related