On Jun 4, 2009, at 1:01 PM, Steve Jaffe wrote:
>
> Suppose I have a vector of strings. I'd like to convert this to a
> vector of
> numbers if possible. How can I tell if it is possible?
>
> as.numeric() will issue a warning if it fails. Do I need to trap this
> warning? If so, how?
>
> In other words, my end goal is a function that takes a vector of
> strings and
> returns either a numeric vector or the original vector. Assuming this
> doesn't already exist, then to write it I'd need a function that
> returns
> true if its input can be converted to numeric and false otherwise.
>
> Any suggestions will be appreciated.
In the case of as.numeric(), it will return NA for any elements in the
vector that cannot be coerced to numeric:
> as.numeric(c("a", "1", "c", "2"))
[1] NA 1 NA 2
Warning message:
NAs introduced by coercion
So there are at least three scenarios:
1. All of the elements can be coerced
2. Some of the elements can be coerced
3. None of the elements can be coerced
You could feasibly do something like this, which will suppress the
warning, so there is no textual output in the case of a warning:
> suppressWarnings(as.numeric(c("a", "1", "c",
"2")))
[1] NA 1 NA 2
Then you just need to check to see if any() of the elements are not
NAs, which means that at least one value was successfully coerced:
NumCheck <- function(x)
{
Result <- suppressWarnings(as.numeric(x))
if (any(!is.na(Result))) TRUE else FALSE
}
> NumCheck(c("a", "1", "c", "2"))
[1] TRUE
> NumCheck(letters[1:4])
[1] FALSE
> NumCheck(c("1", "2", "3", "4"))
[1] TRUE
Alter the internal logic in the function relative to NA checking
depending up what you may need.
HTH,
Marc Schwartz