14

Is there a simple way to convert data in a dataframe from fraction to decimal format? I have a column of data that that's been recorded as a fraction:

Levels: 1/2 1/3 1/4 1/5 1/8 2/3

Is there a quick way to convert it to .5 .333 25 .2 .125 .67?

Nan
  • 446
  • 4
  • 14

1 Answers1

25

Here's a way I've done that in the past.

> frac <- c("1/2","1/3","1/4","1/5","1/8","2/3")
> sapply(frac, function(x) eval(parse(text=x)))
      1/2       1/3       1/4       1/5       1/8       2/3 
0.5000000 0.3333333 0.2500000 0.2000000 0.1250000 0.6666667 
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
  • 2
    Nice solution. Might need to use `eval(parse(text=as.character(x)))` if fraction read as factor. – jogall Apr 11 '19 at 10:11