Skip to content

Instantly share code, notes, and snippets.

@bearloga
Created July 29, 2020 14:09
Show Gist options
  • Save bearloga/4f76d5a7f2842be7414ac54de6ea7622 to your computer and use it in GitHub Desktop.
Save bearloga/4f76d5a7f2842be7414ac54de6ea7622 to your computer and use it in GitHub Desktop.
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