[R] is.numeric

Torsten Hothorn Torsten.Hothorn at rzmail.uni-erlangen.de
Thu Feb 20 11:17:06 CET 2003


> Hi,
> I have a vector, which contains both strings and numbers, e.g.
>
> > foo <- c("str1",1234,"str2",0.9876)
>

R> foo <- list("str1",1234,"str2",0.9876)
R> lapply(foo, is.numeric)
[[1]]
[1] FALSE

[[2]]
[1] TRUE

[[3]]
[1] FALSE

[[4]]
[1] TRUE


using lists is maybe the better solution.

Torsten

> 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
>
>




More information about the R-help mailing list