knitr - change code indentation - r

I am working on a two-column (Rnw, latex) document where the width is at a premium. By default knitr indents the code blocks by 4 spaces. How can I reduce this default indentation?
Many thanks
David

Either do not reformat the code (use the chunk option tidy=FALSE) and manually indent by two spaces,
<<tidy=FALSE>>=
if (TRUE) {
# code here
}
#
or set the R option reindent.spaces to a smaller value, e.g.
options(reindent.spaces = 2)
This option is passed to the formatR package to reindent your code, and knitr uses formatR to reformat your R code by default.

Related

knitr - inline code chunk of foreign engine

I've written a knitr engine to process Maxima code (as part of a package), which works for "regular" chunks just fine, e.g.:
```{maxima}
1+1;
```
results in
(%i1) 1+1;
# (%o1) 2
However, when I try to get the output printed inline, such as
`maxima 1+1;`
It gets printed literally: maxima 1+1;
The R Markdown Cookbook explicitly says
inline: processing output from inline R expressions.
So I guess this is not meant be working (yet), but I wanted to ask here if there is a way to do this/ workaround before filing a feature request at github.

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"

pandoc.convert pdf formatting in R

I am new to R and am trying to convert a markdown document to PDF using the Pandoc.convert function. Pandoc.convert creates the PDF just fine, although the border on the document is ridiculously large. Is there a way to set the border in Pandoc.convert to a smaller border?
Example used:
Pandoc.convert(f="myfile.md", format="pdf", options="-s")
I have tried looking in the Pander package help, and on the Pander site and found no result for Pandoc.convert.
There are three option in pandoc, including: -V geometry:margin=1in
Although, I have found none for Pandoc.convert specifically. Is this even possible with just the Pandoc.convert command, without getting into LaTeX?
Pass any number of further options to Pandoc simply by extending your options argument, e.g.:
Pandoc.convert(f="myfile.md", format="pdf", options="-s -V geometry:margin=1in")

Auto-format R code in RStudio

Is there any possibilities for auto-formatting code in RStudio?
I found this, but it is not connected with RStudio.
Also it is desirable that it be customizable formatting.
update: June-22-2018
Thank you #Lorenz#kirill#yuhi for styler package. I have used it for a while. The simplest after installation of the package is to just use
scroll to Addin --> style active file
Customization options via interface would give some control on styling we prefer.
Rstudio can now format code to look neat. Select the lines of interest and then navigate to Code >> Reformat code or use the keyboard shortcut Ctrl + Shift + A.
or just run the style directory command to style all the files in the directory.
styler::style_dir()
update:
This is a good way to re-structure the code, but it breaks at , for the elements of a vector. For few this is OK, but with many elements passed to a vector, it is overkill:
x <- c(
"p.G12C",
"p.F121S",
"p.P124S",
"p.P124L",
"p.E13D",
"p.E203K",
"p.Q209P",
"p.Q209P",
"p.Q209L"
)
Update: R-Studio Version 0.99.893
There is a new feature that has been added by R-studio Addins. Part of this addins, now you can add #yuhi formatR as an Addin. This is more tidy and cleaner way to structure code than the built-in code >> Refromat code. However, the drawback with the Addin Reformat R Code it throws an error for Rshiny codes.
First CTRL+A, then CTRL+SHIFT+A.
If on a Mac, use ⌘ instead of CTRL.
Go to the Code menu and select
Reindent Lines
Under my OS, this has the shortcut Ctrl + I.
The package styler can format R code and you can access it via a RStudio Addin that allows formatting the active file, the highlighted code, the package and more. A distinguishing feature is its flexibility, as the transformation of code according to a style guide is done separately from specifying the style guide. This allows styling according to arbitrary style guide. As of version 1.2.0, this also holds for the Addin.
We've implemented the tidyverse style guide while allowing for quite some flexibility in styling. Also, the pipe, tidyeval syntax and more is handled properly. You can read an introduction in this blog post.
If you don't want to follow the tidyverse style guide, you can have a look at the vignette 'Customizing Styler' that describes how you can implement an arbitrary style guide. In this vignette, I show how you can implement a style guide consisting of one rule: Always break the line before {. Hope that helps.
Disclosure: I am the maintainer of styler.
Use the formatR library (see documentation):
install.packages("formatR")
library("formatR")
tidy_eval("filename.R")
To add to the great answers that were already given: You can use the styler package in combination with the shrtcts package to enable Format on Save which is still not officially supported by RStudio.
Use the command shrtcts::edit_shortcuts() in the RStudio Console to open the file where you define your custom shortcuts.
Paste the following code inside that file (set your preferred keybinding in the #shortcut line).
#' Format on Save
#'
#' #description
#' Format Document with styler Package and Save Document.
#' #interactive
#' #shortcut Cmd+S
function() {
# format only .R and .Rmd files, but save all file types
file_type <- tools::file_ext(rstudioapi::getActiveDocumentContext()$path)
if (file_type %in% c("R", "Rmd", "qmd")) {
styler:::style_active_file() |>
capture.output() |>
invisible()
}
rstudioapi::documentSave() |>
capture.output() |>
invisible()
}
This solution uses the native pipe |> and thus requires R 4.1.
You can of course just define separate variables in each line or use the magrittr pipe if you use earlier versions of R.
Use the command shrtcts::add_rstudio_shortcuts(set_keyboard_shortcuts = TRUE) in the RStudio Console to add the new shortcut with its assigned keybinding. Then restart RStudio.
With this configuration pressing Cmd+S formats the active .R or .Rmd document with the styler package and saves the formatted version afterwards.
Files of all other types are saved without formatting, but you could easily extend the code above with a package that formats e.g. .md or .py files as well.
There exist cases where this approach code does not have the desired effect, for instance it does not work for new Untitled files or when your current R session is busy.

Using Sexpr{} within \SweaveInput{}

I have this 2 lines of code which I run with R Sweave function.
\SweaveInput{samples.rnw}
\SweaveInput{\Sexpr{args$samples}}
The first line leads to the inclusion of the content of the corresponding file, while the second just causes evaluation of the Sexpr{} term but nothing else.
What I want is both: first let evaluate the Sexpr{} term and afterwards do the inclusion of the respective file content.
How do solve this ?
Thanks
If you use the knitr package, the solution would be simply
<<child='samples.rnw'>>=
<<child=args$samples>>=
#
Sweave is much weaker than knitr in terms of programmability. For example, knitr allows the chunk options to be any valid R expressions, which is the reason why we can write child=args$samples here; knitr will evaluate the chunk options just like function arguments.
BTW, the child option is equivalent to \SweaveInput{}, but I strongly discourage the use of the pseudo LaTeX command. For more about Sweave vs knitr, see http://yihui.name/knitr/demo/sweave/

Resources