[R] Conversion from expression to numeric

Paul Smith phhs80 at gmail.com
Thu Nov 23 18:30:17 CET 2006


On 23 Nov 2006 18:20:17 +0100, Peter Dalgaard <p.dalgaard at biostat.ku.dk> wrote:
> > I am trying to convert from the type "expression" to the type
> > "numeric". The following works:
> >
> > > x <- expression(6.2)
> > > as.numeric(as.character(x))
> > [1] 6.2
> >
> > However, the following does not work:
> >
> > > x <- expression(62/100)
> > > as.numeric(as.character(x))
> > [1] NA
> > Warning message:
> > NAs introduced by coercion
> >
> > Any idea about how to deal with the second case?
>
> Well, you could start by watching where you are going...
>
> > x <- expression(62/100)
> > x
> expression(62/100)
> > as.character(x)
> [1] "62/100"
>
> and as.numeric wouldn't know dashes about strings that contain
> slashes...
>
> eval(x) might be closer to the mark.

Thanks, Peter. I did not know about the existence of the command
'eval', in spite of the fact of having searched the Internet for a
solution for my problem.

'eval' seems not working in connection with Ryacas:

> library(Ryacas)
> x <- yacas("2/3*5/7")
> x
expression(10/21)
> eval(x)
expression(10/21)
>

To work, one has to do the following:
> eval(x)
expression(10/21)
> eval(as.expression(x))
[1] 0.4761905

Paul



More information about the R-help mailing list