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

From: Charilaos Skiadas <skiadas_at_hanover.edu>
Date: Sun, 13 May 2007 08:58:55 -0400

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



R-help_at_stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Sun 13 May 2007 - 13:11:07 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Sun 13 May 2007 - 14:31:04 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.