Skip to content

Instantly share code, notes, and snippets.

@bearloga
Created Jul 29, 2020
Embed
What would you like to do?
knitr engine for sympy code
---
title: "Sympy Engine"
output: html_notebook
editor_options:
chunk_output_type: inline
---
Assuming the "sympy" knitr engine has been registered:
```{sympy, results='asis'}
from sympy import *
x = symbols('x')
a = Integral(cos(x) * exp(x), x)
Eq(a, a.doit())
```
knitr::knit_engines$set(
sympy = function(options) {
# intercept the chunk code
code <- options$code
output <- paste0("output = ", code[length(code)]) # grab last line
code <- c(
code[-length(code)], # sans last line
output,
"print('$' + latex(output) + '$')"
)
options$code <- code
options$engine <- "python"
reticulate::eng_python(options)
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment