0

I am having a variable holding value a <- " 1/2". how to convert it into numeric value like this b <- 1/2. And from 'b' I want to extract 1.

is it possible to extract 1 from "a" without converting it into numeric?

Note: Here my string(a) contains space before 1.

1 Answers1

3

We can use eval(parse

b <- eval(parse(text=a))
b
#[1] 0.5

This could be converted to fractions class using library(MASS)

library(MASS)
fractions(b)
#[1] 1/2

If the post is to remove the space alone

sub('^\\s+', '', a)
#[1] "1/2"

Update

If we need to extract 1 from 'a'.

 gsub('\\/.*|\\s+', '', a)
 #[1] "1"
akrun
  • 874,273
  • 37
  • 540
  • 662