# Re: [S] How to make a character a number?

Fri, 10 Apr 1998 10:19:40 +0930

Timothy Johnson writes:
| This is something I probably should know but here it is.
| Suppose that I have
|
| > x
| [1] "3/4"
| > is.character(x)
| [1] TRUE
|
| but what I want is to transform "3/4" such that it is numeric.
| That is,
|
| > x
| [1] 0.75
| > is.numeric(x)
| [1] TRUE
|
| So, what is the solution to x <- somefunction(x)?

That's a `vulgar' sort of thing to do, Timothy. Try this

vulgar <- function(vf)
switch(as.character(length(vf)),
"0" = numeric(0),
"1" = eval(parse(text = vf)),
eval(parse(text = paste("c(",
paste(vf, collapse= ","),
")", collapse = "")))
)

Here it is in action:

> vulgar("3/4")
[1] 0.75
> v <- paste(1:5, 3, sep="/")
> v
[1] "1/3" "2/3" "3/3" "4/3" "5/3"
> vulgar(v)
[1] 0.33333 0.66667 1.00000 1.33333 1.66667

Using parse() is a bit of an overkill in fact, but it is portable
and if you don't use it too much nobody will notice.

Bill

```--
Bill Venables, Head, Dept of Statistics,    Tel.: +61 8 8303 5418
University of Adelaide,                     Fax.: +61 8 8303 3696