Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding NAs in as.numeric()

Tags:

r

na

If I did this, I get correct result:

a <- c("10","28","3")
which(as.numeric(a) == min(as.numeric(a)))
[1] 3

But if there is NAs in the vector, then there is a problem

a <- c("10","28","3","NA")
which(as.numeric(a) == min(as.numeric(a)))
integer(0)
Warning messages:
1: In which(as.numeric(a) == min(as.numeric(a))) :
  NAs introduced by coercion
2: In which(as.numeric(a) == min(as.numeric(a))) :
  NAs introduced by coercion
like image 473
Selvam Avatar asked Oct 23 '12 01:10

Selvam


1 Answers

Two things.

First, there's a difference between the character string "NA" and the R data representation for missing values, NA. Remove the quotes around NA in your example to see:

a <- c("10","28","3",NA)

Second, when you're using min with actual missing values (i.e. not the character strings "NA") you'll want to use na.rm = TRUE:

which(as.numeric(a) == min(as.numeric(a),na.rm = TRUE))
like image 197
joran Avatar answered Sep 23 '22 00:09

joran