Skip to content
Back to formatted view

Raw Message

Message-ID: <CACxE24n8pQiFaaW9UgBTFy1q0NM5Hv4rDD4BDhi-=fqCr_c4=Q@mail.gmail.com>
Date: 2011-10-19T07:14:55Z
From: Erin Hodgess
Subject: converting string fractions to numerics
In-Reply-To: <4E9E770E.8070404@xtra.co.nz>

Here is another possibility:

> xxx
[1] "pi/2" "1/2"
> sapply(strsplit(xxx,split="/"),
+ function(x) {
+ x <- ifelse(x=="pi",pi,x)
+ as.numeric(x[1])/as.numeric(x[2])
+ }
+ )
[1] 1.570796 0.500000
>

Thanks for everyone's help!

Sincerely,
Erin


On Wed, Oct 19, 2011 at 2:06 AM, Rolf Turner <rolf.turner at xtra.co.nz> wrote:
> On 19/10/11 19:30, Erin Hodgess wrote:
>>
>> Dear R People:
>>
>> Suppose I have the following:
>>
>> "pi/2"
>>
>> and I would like it to be 1.57.....
>>
>> Using as.numeric, here is my result:
>>
>>> as.numeric("pi/2")
>>
>> [1] NA
>> Warning message:
>> NAs introduced by coercion
>>>
>>
>> Is there a way to produce the numeric result, please?
>
> Same answer: parse --- despite what fortune() says.
>
> s <- "pi/2"
> eval(parse(text=s))
> [1] 1.570796
>
> ? ? ? ?cheers,
>
> ? ? ? ? ? ? ? ?Rolf
>



-- 
Erin Hodgess
Associate Professor
Department of Computer and Mathematical Sciences
University of Houston - Downtown
mailto: erinm.hodgess at gmail.com