Rob Creel
Rob Creel

Reputation: 343

How should I print fractions in a dataframe in Rmarkdown?

I'm using RMarkdown to write a statistics exam, and I would like to print a discrete probability distribution in a table. I'm using the MASS library's fractions function because I want to print the probabilities as fractions. I'm using knitr's kable function to format the table. Here is a MWE of my code:

  ---
  output: pdf_document
  ---

  ```{r demo}
  library(knitr)
  library(MASS)
  n <- 5
  x <- 1:n
  p <- fractions(rep(1/n, n))
  df <- data.frame(x = x, p = p)
  kable(df)
  ```

I expect the values in the p column to be printed as fractions, but they print as decimals. How may I achieve my desired result?

Upvotes: 2

Views: 991

Answers (1)

ravic_
ravic_

Reputation: 1831

The easiest way would be to create a string column before posting the output to kable().

df <- data.frame(x = x, p = p)
df$fr <- as.character(df$p)
kable(df)

Upvotes: 4

Related Questions