How to convert R expressions to LaTeX/TeX without using a CAS? - r

I would like to be able to convert R expressions (ex. 1/2*x^2) or formulas into a character string that contains the LaTeX (ex. "\frac{1}{2} \times x^{2}" - or something similar). I know that expression() can be used for something similar, generating mathematical notation in figures, but I'm not sure how to convert a similar type of expression into LaTeX. I want to be able to include this into a Sweave document.
Please give an example (like with the 1/2*x^2), instead of just saying "use the tikzDevice package". It sounds like the Hmisc package might be able to do what I want, but I haven't figured out how yet.
I'm wanting to avoid using a CAS (computer algebra system), because I want it not have to rely on a complex external application, like that Ryacas uses, and want it to be able to run quickly.

latexTranslate provides valid LaTeX output from string input but only partial expansion. The translation of x/y will not be converted to the prefix version, \frac {1} {2}.
require(Hmisc)
latexTranslate("1/2*x^2")
#[1] "1/2*x$^{2}$"

Related

How to write special characters in Julia code

Recently I have seen Julia code like this with special characters:
How can I write Julia code like this? Do I need to have a special editor or can I do this also with e.g. Notepad++?
Julia allows you to use various Unicode symbols for variable and function names, and it makes sense in a lot of the scientific domains Julia is used in, making the code be more alike the scientific notation. (It's sometimes called "executable math" for this reason, though at this point it's more like "executable scientific notation".)
However, in any new code you write, it's not generally necessary to use these symbols, and you can write the code with the basic ASCII characters. Julia language and its standard libraries always provide ASCII equivalents for the Unicode functions they use.
For eg., ⊻ is the XOR character, and you can write 2 ⊻ 11 to get the XOR of the two numbers. But you can also instead write xor(2, 11) to get the same result, and they're exactly equivalent to the language. It's considered good practice for external packages as well, to provide their interface in terms of ASCII-typable names to the extent possible, even if internally Unicode-only names are used.
With that said, if you find you do need to work with code that uses such Unicode symbols, there are a few options:
Option 1: Autohotkey-script for converting LaTeX-like input to unicode characters.
Usually, the way to enter these character in Julia is using LaTeX-like syntax, for eg. \epsilon for ϵ. The AutoHotKey script provided here gives somewhat similar functionality, allowing you to type LaTeX-like input and converting it automatically into the corresponding symbols.
Option 2: A copy-paste list of symbols
This is pretty ad-hoc, but can work for situations where you just need to edit some existing code. You can use a clipboard manager like ClipX, or Win10's inbuilt one, to keep a copy of all the symbols the script uses. At any point, you can choose and insert the particular symbol you need.
Option 2a: Copy-paste from the REPL/Jupyter/Pluto
I'll put this option too here since it uses the clipboard as well. This makes use of the usual workflow for writing Julia code - you'll probably want to try out the code in the REPL or in a notebook anyway, so you can use the tab-completion features there, and then copy that code into your editor. Julia has a clipboard function too, so after trying out median(sin.(-ℯ:0.01:π)) in the REPL, you can surround that in triple quotes and pass it to clipboard like this: """median(sin.(-ℯ:0.01:π))""" |> clipbaord from the REPL itself.
Option 3: Use JuliaEditorSupport/julia-NotepadPlusPlus
This is sort of the "official" option, but only the syntax highlighting file has been updated recently, and the quality and reliability of the Autohotkey script here isn't clear. I'd be hesitant to recommend this option.
Option 4: Use a better supported editor
It's hard to let go of familiar tools, but in this case, this is probably the most reliable option long term. Julia for VSCode is probably the best supported editor right now, but the plugins for Vim and Emacs are also pretty good. If VS Code is too heavy (and Vim and Emacs unfamiliar), you can also try the plugin for Sublime Text which should be both easy to use and light.

Knitr - Define Latex commands that call R functions using Sexpr

I'm basically wondering how to define a new Latex command such that it allows the nesting of Sexpr and some other R function, where the Latex argument is an R object.
As fortunute happenstance, the idea somewhat is transmitted by the new command structure given below:
\newcommand{\SomeLatexCommand}[1]{\Sexpr{"#1"}}
Where fortunately the argument is indeed shown, albeit in string. With this in mind, I was hoping upon the following command:
\newcommand{\SweetLatexCommand}[1]{\Sexpr{SomeRFunction(get("#1"))}}
However, once inside nested inside an R function, #1 is not read as a placeholder for the Latex argument, but instead as an existing R variable.
Is there a way to make the last comand work? Or else, are there also other neat ways to define Latex commands which in turn can call on any R function through R objects?
Good day,
No, you can't do that. The problem is the way knitr works:
R runs the knit() function (or some other knitr function). That function looks through the source for code chunks and \Sexpr calls, executes them, and replaces them with the requested output, producing a .tex file.
Then LaTeX processes that .tex file. R is no longer involved.
Since \newcommand is a LaTeX command, it is only handled in the final stage, after all R evaluation is done.
There may be a way in knitr to specify another "macro" that works the way \Sexpr works, but I don't think there's a way to have several of them.
So what you should do is write multiple functions in R, and call those to do what you want, as \Sexpr{fn1(...)}, \Sexpr{fn2(...)}, etc.
I suppose if you were really determined, you could add an extra preprocessor stage at the beginning, that went through your Rnw file and replaced all strings that looked like \SweetLatexCommand{blah} with \Sexpr{SomeRFunction(get("blah"))} and then called knit(), but that seems like way too much work.

Julia's equivalent to R's ?? (double question-mark help.search across all packages)

In R you can search the documentation by typing a question mark ? or a double question mark ??. How do you search the manual for strings in the Julia REPL?
>?first
No documentation for ‘first’ in specified packages and libraries:
you could try ‘??first’
>??first
In the R console a browser window opens up:
In RStudio the page is opened within the IDE.
The help() function and ? help operator in R provide access to the
documentation pages for R functions, data sets, and other objects,
both for packages in the standard R distribution and for contributed
packages.
The help() function and ? operator are useful only if you already know the name of the function that you wish to use. Other ways to search include apropos and ??
The apropos() function searches for objects, including functions,
directly accessible in the current R session that have names that
include a specified character string.
The ?? operator is a synonym for help.search(). The help.search()
function scans the documentation for packages installed in your
library. The argument to help.search() is a character string or regular expression.
P.S. I intend to answer my own question.
Julia has similar interactive utilties. Julia's main search utility for docstrings is named apropos.
To search the documentation for information about "first" in Julia, you have apropos("first") or equivalently ?"first". Thus ?"first" is roughly equivalent to R's ??.
To search for functions and methods, you can type a singe question mark ?, just as with R. In the Julia REPL, as you type the question mark, the prompt changes to a question mark. If you type "first" it searches through strings, while if you type first without quote-marks, you get a search over variables exported by the modules currently loaded.
Illustration:
help?>"first"
# or equivalently:
julia>apropos("first")
help?>first
If you search for a string, case is ignored. If you want to search within the DataFrames module, type using DataFrames before searching.
This also works in Visual Studio Code and Atom:

Jupyter/IPython: how to get results in traditional mathematical notation?

I have been using WxMaxima for my symbolic calculations for a while now. The good thing about WxMaxima is that you can get formatted outputs right in the program and then export them to LaTeX format with a click of the mouse.
Now I want to try the Jupyter/Ipython plus sympy for multiple reasons. I know how to use display(Math(r' some LaTeX math here ')) but what I want is to have the result/output of a cell in a nice mathematical form; something like the TraditionalForm[] command in Mathematica.
I would appreciate if you could help me know if/how I can get that right in a Jupyter notebook?
I think I found the proper solution and it is a sympy feature rather than Jupyter/IPython one. As explained here:
If all you want is the best pretty printing, use the init_printing() function. This will automatically enable the best printer available in your environment.
and
In the [Jupyter/]IPython notebook, it will use MathJax to render LATEX.
Then one can right click on the output and select Show Math As > Tex commands:
to get the LaTeX output.
P.S. A more proper formatting can be achieved via galgebra library. I will look into that and add it here later.

Function to sanitize strings for LaTeX compilation?

While xtable() has a sanitize.text.function argument which allows to sanitize strings with special charaters to stop LaTeX compilation from breaking in Sweave/knitr documents, the package does not export the function to the userspace.
How can I sanitize strings like asdf_text outside of the xtable context, so as to have it transformed to something like asdf\_text? (If possible I would prefer a small, self-contained solution.)
Unless I misunderstand your question, I think you've overlooked latexTranslate, which is also in the Hmisc package (and documented on the same help page as ?latex):
‘latexTranslate’ translates particular items in character strings
to LaTeX format, e.g., makes ‘a^2 = a\$^2\$’ for superscript
within variable labels. LaTeX names of greek letters (e.g.,
‘"alpha"’) will have backslashes added if ‘greek==TRUE’. Math
mode is inserted as needed. ‘latexTranslate’ assumes that input
text always has matches, e.g. ‘[) [] (] ()’, and that surrounding
by ‘\$\$’ is OK.
library("Hmisc")
latexTranslate("asdf_text")
## [1] "asdf\\_text"
latexTranslate("a^2")
## [1] "a$^{2}$"
Thus far I found package reportRx which provides sanitizestr():
Sanitizes strings to not break LaTeX
Strings with special charaters will break LaTeX if returned 'asis' by knitr. This happens every time we use one of the main reportRx functions. We first sanitize our strings with this function to stop LaTeX from breaking.
require(reportRx)
sanitizestr("asdf_text")
## [1] "asdf\\_text"
My gripe however is that it comes with quite a number of dependencies...
Another solution is tikzDevice which provides sanitizeTexString(), and has many fewer mandatory dependencies:
Replace LaTeX Special Characters in a String
This function is used by tikzDevice when sanitize=TRUE to replace special LaTeX characters [..]
require(tikzDevice)
sanitizeTexString("asdf_text")
## [1] "asdf{\\_{}}text"

Resources