[R] is.numeric
Frank E Harrell Jr
fharrell at virginia.edu
Thu Feb 20 12:49:02 CET 2003
On Thu, 20 Feb 2003 10:58:46 +0100
Arne Henningsen <ahenningsen at email.uni-kiel.de> wrote:
> Hi,
> I have a vector, which contains both strings and numbers, e.g.
>
> > foo <- c("str1",1234,"str2",0.9876)
>
> I want to know if a distinct element of the vector is a string or a number and
> took "is.numeric", but
>
> > is.numeric(foo[2])
> [1] FALSE
>
> because R treats the numbers in a mixed vectors as strings:
>
> > foo
> [1] "str1" "1234" "str2" "0.9876"
>
> As a workaround I use:
>
> > !is.na(as.numeric(foo[2]))
> [1] TRUE
> > !is.na(as.numeric(foo[1]))
> [1] FALSE
> Warning message:
> NAs introduced by coercion
>
> This works, but I always get the spurious warning messages. Do you know a
> better way or a way to suppress these warning messages?
>
> Thanks,
> Arne
>
> --
> Arne Henningsen
> Department of Agricultural Economics
> Christian-Albrechts-University Kiel
> 24098 Kiel, Germany
> Tel: +49-431-880-4445
> Fax: +49-431-880-1397
> ahenningsen at email.uni-kiel.de
> http://www.uni-kiel.de/agrarpol/ahenningsen.html
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> http://www.stat.math.ethz.ch/mailman/listinfo/r-help
This function in the Hmisc library may help:
all.is.numeric <- function(x, what=c('test','vector')) {
what <- match.arg(what)
old <- options(warn=-1)
on.exit(options(old))
xs <- x[x!='' & x!=' ']
isnum <- !any(is.na(as.numeric(xs)))
if(what=='test') isnum else if(isnum) as.numeric(x) else x
}
--
Frank E Harrell Jr Prof. of Biostatistics & Statistics
Div. of Biostatistics & Epidem. Dept. of Health Evaluation Sciences
U. Virginia School of Medicine http://hesweb1.med.virginia.edu/biostat
More information about the R-help
mailing list