[R] Quick Question about R

(Ted Harding) ted.harding at nessie.mcc.ac.uk
Wed Jan 31 20:59:36 CET 2007


On 31-Jan-07 Konrad wrote:
> Hello,
> Is there a way to convert a character to a number with out getting a
> warning?  I have a vector that has both numbers and letters in it and I
> need to convert it to only numbers.  At the moment I'm using as.numeric
> but it is generating a warning when it converts a letter.  Is there
> another function out there that will do what I need or is there a way
> to turn off the warnings as I don't want the warning to be displayed to
> the end user?

Have a look at the entries "warn" and "warning.expression" under
?options

In particular:

> options()$warn
[1] 0

> x <- c(1,2,"C",4,"E",6,"G")
> as.numeric(x)
[1]  1  2 NA  4 NA  6 NA
Warning message: 
NAs introduced by coercion 

> old.warn <- options()$warn
> options(warn = -1)
> as.numeric(x)
[1]  1  2 NA  4 NA  6 NA

> options(warn = old.warn)
> as.numeric(x)
[1]  1  2 NA  4 NA  6 NA
Warning message: 
NAs introduced by coercion 
> 

Note that options(warn = -1) turns off all warning messages everywhere,
so you may want to bracket your calls to as.numeric() in the way shown
above, to avoid intefering with other cases where you may want the
user to see the warning.

Hoping this helps,
Ted.

--------------------------------------------------------------------
E-Mail: (Ted Harding) <ted.harding at nessie.mcc.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 31-Jan-07                                       Time: 19:59:33
------------------------------ XFMail ------------------------------



More information about the R-help mailing list