Christopher Tan
Christopher Tan

Reputation: 53

TeXForm from Ryacas package as R markdown output

I was attempting to use the Ryacas package in generating math questions involving fractions. Below is some minimal code in R:

a1 = 1
a2 = 2
b1 = 1
b2 = 3

linearFactor1 = x+1
linearFactor2 = x+3

question1 = (1/linearFactor1 + 2/linearFactor2) %>% y_fn("Simplify") %>% y_fn("TeXForm")
question1

Output: ## [1] "\\frac{3 x + 7}{x ^{2} + 5 x + 6} "


I would like to display question with an inline code block as such:

Express $r question1$ in partial fractions.

However, I received an output like this:

enter image description here


When using a multiline to render the math i.e. Express $$r question1$$ in partial fractions, I get an output where the math is rendered correctly:

enter image description here


The question is: Why is there a difference in how R Markdown renders the math, and how can I get it to render as an inline block?

Upvotes: 2

Views: 158

Answers (1)

SBFin
SBFin

Reputation: 362

The trailing space causes a problem in the in-line format $, but not if you render as equation with $$. Remove the trailing space and it should render correctly in RMarkdown. I am not familiar with the package but if that happens with every equation, this is how you would get rid of the trailing space.

# remove trailing whitespace on the right
question1 <- trimws(question1, "r")

Or manually

question1 <- "\\frac{3 x + 7}{x ^{2} + 5 x + 6}"

In the Rmd:

Works in line:

$`r question1`$

Works as equation

$$`r question1`$$

Upvotes: 1

Related Questions