3

Say I have a list of decimals

x <- c(0.55, 0.246, 0.767)

Then I wish to have these converted into fractions out of 10 so that I get

6/10 2/10 8/10

I have come across this which works quite nicely. However, I was wondering if there was a function which would do it?

frac.fun <- function(x, den){ 
  dec <- seq(0, den) / den 
  nams <- paste(seq(0, den), den, sep = "/") 
  sapply(x, function(y) nams[which.min(abs(y - dec))]) 
} 

frac.fun(x, 10) 
#[1] "6/10" "2/10" "8/10"

This is different to other stack overflow questions I've come across since I am interested in there being a common denominator for all my decimals, and interested in specifying what that denominator is.

Thanks!

user7715029
  • 83
  • 1
  • 7
  • 2
    Related https://stackoverflow.com/questions/5046026/print-number-as-reduced-fraction-in-r – akrun Aug 01 '17 at 09:45
  • Possible duplicate of [Print number as reduced fraction in R](https://stackoverflow.com/questions/5046026/print-number-as-reduced-fraction-in-r) – Anders Ellern Bilgrau Aug 01 '17 at 09:48
  • `MASS::fractions` is very likely what you need. However, if instead you need to round to a *specific* denominator, you can also try `paste0((x %/% (1/den)) + (x %% (1/den) > (1/2/den)),"/",den)`. – nicola Aug 01 '17 at 09:50
  • @akrun I saw that, however I want it to be out of 10 always. This function is good as it offers a max.denominator but not a min.denominator as well. Thank you though. – user7715029 Aug 01 '17 at 09:50

1 Answers1

5

Just in case you need to use a more simplified version of the above function

f = function(x, den) {paste0(round(x * den), "/", den)}
x <- c(0.55, 0.246, 0.767)
f(x, 10)

[1] "6/10" "2/10"  "8/10" 
AntoniosK
  • 15,991
  • 2
  • 19
  • 32
  • That is a lot more ideal. Thank you for this. – user7715029 Aug 01 '17 at 09:57
  • Make sure you're happy with the approximations if you decide to use something like this. I mean that 0.55 is not equal to 6/10. The bigger the denominator the closer to the actual value you'll be. As 0.55 = 55/100. – AntoniosK Aug 01 '17 at 09:58
  • Yes, I am baring this in mind. It is to be used for teaching where these concepts of decimal places and /100 are more difficult to understand/visualise. Thank you. – user7715029 Aug 01 '17 at 10:24