Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting numerator and denominator of a fraction in R

Tags:

r

fractions

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.

like image 496
Bonnie Scott Avatar asked Feb 11 '13 20:02

Bonnie Scott


Video Answer


2 Answers

A character representation of the fraction is stored in an attribute:

x <- fractions(0.175)
> strsplit(attr(x,"fracs"),"/")
[[1]]
[1] "7"  "40"
like image 178
joran Avatar answered Sep 28 '22 18:09

joran


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
like image 31
juba Avatar answered Sep 28 '22 17:09

juba