Are there any drawbacks when chunk labels are not quoted? - r

Yihui Xie, the creator of knitr, writes in the official knitr chunk option documentation (emphasis by me):
(...) in theory, the chunk label should be quoted as well, but for the sake of convenience it will be automatically quoted if you did not quote it (e.g. ```{r, 2a} will become ```{r, '2a'})
As I understand this, the results of quoted and unquoted chunk labels should always be the same. Is this really true? Or might there be any (edge) cases where quoting vs. not quoting the chunk labels actually matters?
Especially, I'd like to know if there might be any differences in results if one adheres to the following recommendation also found in the knitr chunk option documentation:
(...) in general it is recommended to use alphabetic characters with words separated by - and avoid other characters (...)

The only edge case I can think of is when your chunk label contains a comma, e.g., a,b. In this case, it has to be quoted as 'a,b', otherwise a will be treated as the chunk label.
Chunk labels are automatically quoted via the internal function knitr:::quote_label(). You may try to find out other possible edge cases by yourself:
> knitr:::quote_label("a")
[1] "'a'"
> knitr:::quote_label("a,b")
[1] "'a',b"
> knitr:::quote_label('"a,b"')
[1] "\"a,b\""
> knitr:::quote_label("a a a,b=1")
[1] "'a a a',b=1"
> knitr:::quote_label("a},b=1")
[1] "'a}',b=1"

Related

Julia: docstrings and LaTeX

Julia has docstrings capabilities, which are documented here https://docs.julialang.org/en/stable/manual/documentation/. I'm under the impression that it has support for LaTeX code, but I'm not sure if the intention is that the LaTeX code should look like code or like an interpretation. In the following, the LaTeX code is garbled somewhat (see rho, for instance) and not interpreted (rho does not look like ρ). Am I doing something wrong?
Is there a way to get LaTeX code look interpreted?
What I mean by interpreted is something like what they do at https://math.stackexchange.com/.
The documentation says that LaTeX code should be wrapped around double back-quotes and that Greek letters should be typed as ρ rather than \rho. But that rather defeats the point of being able to include LaTeX code, doesn't it?
Note: Version 0.5.2 run in Juno/Atom console.
"""
Module blabla
The objective function is:
``\max \mathbb{E}_0 \int_0^{\infty} e^{-\rho t} F(x_t) dt``
"""
module blabla
end
If I then execute the module and query I get this:
With triple quotes, the dollar signs disappear, but the formula is printed on a dark background:
EDIT Follow-up to David P. Sanders' suggestion to use the Documenter.jl package.
using Documenter
doc"""
Module blabla
The objective function is:
$\max \mathbb{E}_0 \int_0^{\infty} e^{-\rho t} F(x_t) dt$
"""
module blabla
end
Gives the following: the LaTeX code appears to print correctly, but it's not interpreted (ρ is displayed as \rho. I followed suggestions in: https://juliadocs.github.io/Documenter.jl/stable/man/latex.html to
Rendering LaTeX code as actual equations has to be supported by whichever software renders your docstrings. So, the short answer to why you're not seeing any rendered equations in Juno is that LaTeX rendering is currently not supported in Juno (as Matt B. pointed out, there's an open issue for that).
The doc"" string literal / string macro is there to get around another issue. Backslashes and dollar signs normally have a special meaning in string literals -- escape sequences and variable interpolation, respectively (e.g. \n gets replaced by a newline character, $(variable) inserts the value of variable into the string). This, of course, clashes with the ordinary LaTeX commands and delimiters (e.g. \frac, $...$). So, to actually have backslashes and dollar signs in a string you need to escape them all with backslashes, e.g.:
julia> "\$\\frac{x}{y}\$" |> print
$\frac{x}{y}$
Not doing that will either give an error:
julia> "$\frac{x}{y}$" |> print
ERROR: syntax: invalid interpolation syntax: "$\"
or invalid characters in the resulting strings:
julia> "``\e^x``" |> print
``^x``
Having to escape everything all the time would, of course, be annoying when writing docstrings. So, to get around this, as David pointed out out, you can use the doc string macro / non-standard string literal. In a doc literal all standard escape sequences are ignored, so an unescaped LaTeX string doesn't cause any issues:
julia> doc"$\frac{x}{y}$" |> print
$$
\frac{x}{y}
$$
Note: doc also parses the Markdown in the string and actually returns a Base.Markdown.MD object, not a string, which is why the printed string is a bit different from the input.
Finally, you can then use these doc-literals as normal docstrings, but you can then freely use LaTeX syntax without having to worry about escaping everything:
doc"""
$\frac{x}{y}$
"""
function foo end
This is also documented in Documenter's manual, although it is not actually specific to Documenter.
Double backticks vs dollar signs. The preferred way to mark LaTeX in Julia docstrings or documentation is by using double backticks or ```math blocks, as documented in the manual. Dollar signs are supported for backwards compatibility.
Note: Documenter's manual and the show methods for Markdown objects in Julia should be updated to reflect this.
You can use
doc"""
...
"""
This is a "non-standard string literal" used by the Documenter.jl package; see https://docs.julialang.org/en/stable/manual/strings/#non-standard-string-literals.

knitr displaying digits of an integer without scientific notation

when displaying a number with inline-code with more than four digits like
`r 21645`
the result in a knitted html-file is this: 2.164510^{4} (in reality inside the inline-hook there is a calculation going on which results in 21645). Even though I just want it to print the number, like so: 21645. I can easily fix this for one instance wrapping it inside as.integer or format or print, but how do I set an option for the whole knitr-document so that it prints whole integers as such (all I need is to print 5 digits)? Doing this by hand gets very annoying. Setting options(digits = 7) doesnt help. I am guessing I would have to set some chunk-optionor define a hook, but I have no idea how
I already solved it, just including the following line of code inside the setoptions-chunk in the beginning of a knitr document:
options(scipen=999)
resolves the issue, like one can read inside this answer from #Paul Hiemstra:
https://stackoverflow.com/a/25947542/4061993
from the documentation of ?options:
scipen: integer. A penalty to be applied when deciding to print
numeric values in fixed or exponential notation. Positive values bias
towards fixed and negative towards scientific notation: fixed notation
will be preferred unless it is more than scipen digits wider.
If you don't want to display scientific notation in this instance, but also don't want to disable it completely for your knitr report, you can use format() and set scientific=FALSE:
`r format(21645, scientific=FALSE)`
Note that if you type your numeric as integer it will be well formatted:
`r 21645L`
Of course you can always set an inline hook for more flexibility( even it is better to set globally options as in your answer):
```{r}
inline_hook <- function(x) {
if (is.numeric(x)) {
format(x, digits = 2)
} else x
}
knitr::knit_hooks$set(inline = inline_hook)
```

Escaping characters for text mode in AUCTeX [duplicate]

When editing an Sweave document in LaTeX (using the Noweb mode), Emacs knows to "ignore" code that is in <<>>= blocks. However, for interstitial \Sexpr{} blocks, this isn't the case. Given that R references by columns via '$' and LaTeX uses $ to set-off equations, these \Sexpr{} blocks often break the syntax highlighting, like so:
I have a very rudimentary understanding the elisp & Emacs syntax highlighting, but my hope is that it might be possible to add something to .emacs that will disable any parsing/$ detection within \Sexpr{}'s.
I thought emacs with ESS has correct syntax highlighting for Sweave?
Anyway, the easiest "fix" is to just not use the $ operator but [[ instead. For example:
foo$p.value
foo[['p.value']]
Should give the same result. I think foo$p.value is just short for foo[["p.value",exact=FALSE]]
I don't have a fix either, but I'll pass along my workaround, which is to never (well, rarely) do any processing in \Sexpr chunks but instead to store things I want to use in \Sexpr in variables, and to do so in the same chunk I do the main calculations in.
<<echo=FALSE, results=hide>>=
t1 <- chisq.test(someVar)
p1 <- formatC(t1$p.value, format="%f", digits=2)
#
\dots with a $p$-value of \Sexpr{p1}.
While there are some downsides to this, I find it helps me to better keep track of what I want to present, and how I want to present it.
As an aside, consider using formatC instead of round as it can keep significant zeros (ie, 0.10 instead of 0.1).
I have no good answer for you as I am not an Emacs hacker, so I usually do one of two things:
Either add a simple % $ comment at the of the line to "close" the math expression from $ to $,
Or rewrite the expression to not use $-based subsetting:
round(as.numeric(chisq.test(someVar)["p.value"]), 2).

Paste "25 \%" in R for further processing in LaTeX

I want a character variable in R taking the value from, lets say "a", and adding " \%", to create a %-sign later in LaTeX.
Usually I'd do something like:
a <- 5
paste(a,"\%")
but this fails.
Error: '\%' is an unrecognized escape in character string starting "\%"
Any ideas? A workaround would be to define another command giving the %-sign in LaTeX, but I'd prefer a solution within R.
As many other languages, certain characters in strings have a different meaning when they're escaped. One example for that is \n, which means newline instead of n. When you write \%, R tries to interpret % as a special character and fails doing so. You might want to try to escape the backslash, so that it is just a backslash:
paste(a, "\\%")
You can read on escape sequences here.
You can also look at the latexTranslate function from the Hmisc package, which will escape special characters from strings to make them LaTeX-compatible :
R> latexTranslate("You want to give me 100$ ? I agree 100% !")
[1] "You want to give me 100\\$ ? I agree 100\\% !"

Get Emacs to ignore contents of \Sexpr{} command in Sweave document to prevent incorrect $-based syntax highlighting

When editing an Sweave document in LaTeX (using the Noweb mode), Emacs knows to "ignore" code that is in <<>>= blocks. However, for interstitial \Sexpr{} blocks, this isn't the case. Given that R references by columns via '$' and LaTeX uses $ to set-off equations, these \Sexpr{} blocks often break the syntax highlighting, like so:
I have a very rudimentary understanding the elisp & Emacs syntax highlighting, but my hope is that it might be possible to add something to .emacs that will disable any parsing/$ detection within \Sexpr{}'s.
I thought emacs with ESS has correct syntax highlighting for Sweave?
Anyway, the easiest "fix" is to just not use the $ operator but [[ instead. For example:
foo$p.value
foo[['p.value']]
Should give the same result. I think foo$p.value is just short for foo[["p.value",exact=FALSE]]
I don't have a fix either, but I'll pass along my workaround, which is to never (well, rarely) do any processing in \Sexpr chunks but instead to store things I want to use in \Sexpr in variables, and to do so in the same chunk I do the main calculations in.
<<echo=FALSE, results=hide>>=
t1 <- chisq.test(someVar)
p1 <- formatC(t1$p.value, format="%f", digits=2)
#
\dots with a $p$-value of \Sexpr{p1}.
While there are some downsides to this, I find it helps me to better keep track of what I want to present, and how I want to present it.
As an aside, consider using formatC instead of round as it can keep significant zeros (ie, 0.10 instead of 0.1).
I have no good answer for you as I am not an Emacs hacker, so I usually do one of two things:
Either add a simple % $ comment at the of the line to "close" the math expression from $ to $,
Or rewrite the expression to not use $-based subsetting:
round(as.numeric(chisq.test(someVar)["p.value"]), 2).

Resources