[R] how to convert a string vector to a numeric vector

Charilaos Skiadas skiadas at hanover.edu
Sun May 13 14:58:55 CEST 2007


On May 13, 2007, at 7:48 AM, Mihai Bisca wrote:

> Hello all,
>
> I'm new to R and I cannot find a simple answer to a simple question.
> If I have a character vector like v <- c('1/50,'1/2','1/8'...) how can
> I convert it to a numeric vector like vn <- c(0.02,0.5,0.125...). I
> tried as.numeric in various ways and failed miserably. Currently I use
> a function like: for (e in v) { if (e=='1/50') vn<-c(vn,0.02) ...} but
> that feels bad because it needs to be (humanly) modified everytime a
> new fraction appears in v.

The problem is that as.numeric does not expect to see expressions  
that would need evaluation, like 1/50 above, but instead it expects  
to see numbers.

Assuming the entries have always the form a/b, with a and b numbers,  
then you could use this:

vn <- sapply(strsplit(v,"/"), function(x) as.numeric(x[1])/as.numeric 
(x[2]))

If your entries are allowed to be more general expressions, like (1 
+5)/10 or simply 0.2 or whatnot, you could perhaps use:

sapply(parse(text=v), eval)

But I prefer to avoid parse+eval whenever possible.

> Thanks in advance,
>
> -- 
> Mihai.

Haris Skiadas
Department of Mathematics and Computer Science
Hanover College



More information about the R-help mailing list