On my old beat-up TI-83 I can get a reduced fraction representation of a rational real number with the following syntax.
.14>Frac7/50
Is there a similar syntax, function, or CRAN package that will allow me to do this in R?
Best Answer
fractions() in the MASS package does just that:
> library(MASS)> fractions(.14)[1] 7/50
Another possibility is to use reduce.fraction
from phonTools
, but this requires a ratio of whole numbers:
library(phonTools)frac <- function(x) {denom <- 10^(nchar(x %% 1) - 2)num <- trunc(x * denom)reduce.fraction(c(num, denom))}frac(.14)[1] 7 50# for multiple numbers must vectorizevfrac <- Vectorize(frac, "x")vfrac(c(.14, .375))[,1] [,2][1,] 7 3[2,] 50 8
This allows for an easy retrieval of the numerator and denominator and values can easily be formatted to create a fraction:
paste(frac(.14), collapse = "/"))[1] "7/50"
#Steps:#1. Convert the data into fractions using fractions() from the MASS package.#2. Convert the matrix to character.#3. Convert to data frame.#4. Then use gt().#Exampleif (!require("gt")) install.packages("gt")if (!require("MASS")) install.packages("MASS")library(gt)library(MASS)#Let us have some data using discrete joint probability distributionJointDist <- function(xvector,yvector){i <- 0j <- 0entries <- matrix(nrow = length(xvector), ncol = length(yvector))for (x in min(xvector):max(xvector)) {i = i+1j <- 0 #reset jfor (y in min(yvector):max(yvector)) {j = j+1entries[i,j] <- (2*x+y)/42 #change the expression according to the given}}entries}xvect <- 0:2yvect <- 0:3#This is the data in decimal formatmydata <- JointDist(xvect, yvect)mydata#This is the data in fraction formatmydata <- fractions(JointDist(xvect, yvect))mydata#Rename the columns and rowscolnames(mydata) <- paste0("yequals_",yvect)rownames(mydata) <- paste0("xequals_", xvect)mydata#Get the marginal function of x and y and combine in the matrix#The last column is the marginal probability function of x#The last row is the marginal probability function of ymydata <- fractions(cbind(mydata, marginalPFx = rowSums(mydata)))mydata <- fractions(rbind(mydata, marginalPFy = colSums(mydata)))mydata#convert to data framedf <- data.frame(Headers = row.names(mydata), mydata)df#Notice that it did not retain the fraction format.gt(df)#The secret is to change mydata to character before converting it to data framemydata <- as.character(mydata)#convert to data framedf <- data.frame(Headers = row.names(mydata), mydata)df#Now, it retains the fraction format.gt(df)#Add some titleif (!require("dplyr")) install.packages("dplyr")library(dplyr)gt(df) %>% tab_header(title = md("**JOINT PROBABILITY DISTRIBUTION**"),subtitle = md("***f(x,y) = (2x+y)/42***"))#That's it!