[R] Quick Question about R
Marc Schwartz
marc_schwartz at comcast.net
Wed Jan 31 21:36:25 CET 2007
On Wed, 2007-01-31 at 20:02 +0000, Ted.Harding at manchester.ac.uk wrote:
> On 31-Jan-07 Benilton Carvalho wrote:
> > suppressWarnings(a <- as.numeric(c(1, 2, pi, "a", 9, "z")))
>
> Of course! Much better!
> Ted.
In the context of my prior reply:
# Bear in mind that the above vector is of class character, not mixed...
> str(c(1, 2, pi, "a", 9, "z"))
chr [1:6] "1" "2" "3.14159265358979" "a" "9" "z"
> class(c(1, 2, pi, "a", 9, "z"))
[1] "character"
Thus:
> grep("[0-9\\.]", Vec, value = TRUE)
[1] "1" "2" "3.14159265358979"
[4] "9"
> as.numeric(grep("[0-9\\.]", Vec, value = TRUE))
[1] 1.000000 2.000000 3.141593 9.000000
or:
> gsub("[A-Za-z]", "", Vec)
[1] "1" "2" "3.14159265358979"
[4] "" "9" ""
> as.numeric(gsub("[A-Za-z]", "", Vec))
[1] 1.000000 2.000000 3.141593 NA 9.000000 NA
The latter solution returns the NA's for non-convertible elements,
whereas the former, only the resultant numerics.
My preference is to be proactive in managing the data rather than
disabling warnings. :-)
HTH,
Marc Schwartz
More information about the R-help
mailing list