Created
July 29, 2020 14:09
-
-
Save bearloga/4f76d5a7f2842be7414ac54de6ea7622 to your computer and use it in GitHub Desktop.
knitr engine for sympy code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--- | |
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()) | |
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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