Getting the numerator and denominator of a fraction in R

Using the fractions function in the MASS library, I can convert the decimal to fractions:

 > fractions(.375) [1] 3/8 

But how can I extract the numerator and denominator? The help for fractions mentions the "fracs" attribute, but I cannot access it.

+6
source share
2 answers

The symbolic representation of the fraction is stored in the attribute:

 x <- fractions(0.175) > strsplit(attr(x,"fracs"),"/") [[1]] [1] "7" "40" 
+7
source

You can get the fracs attribute from the fraction object as follows, but this is just a symbolic representation of your fraction:

 x <- fractions(.375) attr(x, "fracs") # [1] "3/8" 

If you want to access the numerator and denominator values, you can simply split the line with the following function:

 getfracs <- function(frac) { tmp <- strsplit(attr(frac,"fracs"), "/")[[1]] list(numerator=as.numeric(tmp[1]),denominator=as.numeric(tmp[2])) } 

What you can use as follows:

 fracs <- getfracs(x) fracs$numerator # [1] 3 fracs$denominator # [1] 8 
+4
source

All Articles