Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - 'NA' text treated as N/A

Tags:

text

r

na

I have a data frame in R including country iso codes. The iso code for Namibia happens to be 'NA'. R treats this text 'NA' as N/A.

For example the code below gives me the row with Namibia.

test <- subset(country.info,is.na(country.info$iso.code))

I initially thought it might be a factor issue, so I made sure the iso code column is character. But this didn't help.

How can this be solved?

like image 255
slo0t Avatar asked Dec 09 '25 10:12

slo0t


1 Answers

This probably relates to how you read in the data. Just because it's character doesn't mean your "NA" isn't an NA, e.g.:

z <- c("NA",NA,"US")
class(z)
#[1] "character"

You could confirm this by giving us a dput() of (part of) your data.

When you read in your data, try changing na.strings = "NA" (e.g., in read.csv) to something else and see if it works.

For example, with na.strings = "":

read.table(text="code country
NA  Namibia
GR  Germany
FR  France", stringsAsFactors=FALSE, header=TRUE, na.strings="")
#   code country
# 1   NA Namibia
# 2   GR Germany
# 3   FR  France

Make sure to check that the use of "" doesn't result in changing anything else. Else, you can use a string that will definitely not occur in your file like "z_z_z" or something like that.. You can replace the text=.. with your file name.

like image 99
Thomas Avatar answered Dec 12 '25 02:12

Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!