Using the function fractions
in the library MASS, I can convert a decimal to a fraction:
> fractions(.375)
[1] 3/8
But then how to I extract the numerator and denominator? The help for fractions
mentions an attribute "fracs", but I can't seem to access it.
A character representation of the fraction is stored in an attribute:
x <- fractions(0.175)
> strsplit(attr(x,"fracs"),"/")
[[1]]
[1] "7" "40"
You can get the fracs
attribute from your fraction object the following way, but it is just the character representation of your fraction :
x <- fractions(.375)
attr(x, "fracs")
# [1] "3/8"
If you want to access numerator and denominator values, you can just split the string with the following function :
getfracs <- function(frac) {
tmp <- strsplit(attr(frac,"fracs"), "/")[[1]]
list(numerator=as.numeric(tmp[1]),denominator=as.numeric(tmp[2]))
}
Which you can use this way :
fracs <- getfracs(x)
fracs$numerator
# [1] 3
fracs$denominator
# [1] 8
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With