user7715029
user7715029

Reputation: 83

Function in R to convert a decimal to a fraction with a specified denominator

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!

Upvotes: 3

Views: 4517

Answers (1)

AntoniosK
AntoniosK

Reputation: 16121

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" 

Upvotes: 5

Related Questions