tags:

views:

55

answers:

2

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?

+6  A: 

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
A: 

A related interesting question is how to convert from decimals back to fractions, if you suspect that your data was originally a simple fraction. I have some Perl code that does this for me at the command line using the method of continued fractions, perhaps someday I'll convert this to R and share it.

Ken Williams