Auto-format R code in RStudio - r

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.

Related

R bookdown: list of abbreviations with LaTeX nomenclature package

Generating an index in R bookdown works perfectly well.
Adding a list of abbreviations with the nomenclature package is more difficult:
I added to preamble.tex
\usepackage{nomenclature}
\makenomenclature
And then I include a file calling the \printnomenclature macro via the after_body include option in the yaml header.
Actually, I already have a pretty good idea, what the problem is:
Usually, one calls makeindex when generating the nomenclature list with LaTeX. This magically works for the index, but for the nomenclature package, there seems to be a need for some manual work.
Since RStudio does not know about special makeindex calls, you could install a tool like latexmk and configure RStudio to use that by putting Sys.setenv(RSTUDIO_PDFLATEX = "latexmk") somewhere in your main Rmd file, c.f.
Is there a way to add chapter bibliographies using bookdown?
[Not tested since you do not provide a minimal example.]

Linking to other packages in documentation in roxygen2 in R

I am wondering it there exists a method to link to function from other package when I'm trying to write a documentation for new package using roxygen2.
Something like \link{pck=PACKAGE_NAME, fun=FUNCTION_NAME}?
You have to type \link[pkg]{function} e.g. \link[stringi]{stri_c}
Roxygen2 now also supports documentation written in markdown.
The markdown syntax is for the link is [foo::bar()] which is translated to
\code{\link[foo:bar]{foo::bar()}} in the generated .Rd file. (See Roxygen2 vignette.)
Note that you may need to specifically turn on Markdown support by writing Roxygen: list(markdown = TRUE) in your DESCRIPTION file, or by putting an #' #md comment if you want to enable markdown only for a specific man page. This is also explained at the very top of the linked vignette. (Thanks to #Tjebo for the comment)
Note that there are two colons in the markdown version whereas there is only one colon in the Rd version.
There are two ways to achieve this, using:
1. .Rd syntax
From "R packages" book:
\code{\link{function}} - function in this package.
\code{\link[MASS]{abbey}} - function in another package.
\link[=dest]{name} - link to dest, but show name.
\code{\link[MASS:abbey]{name}} - link to function in another package, but show name.
\linkS4class{abc} - link to an S4 class.
2. markdown syntax
From roxygen2 vignette
roxygen2 comment
description
generated Rd code
[func()]
func() in this package
\code{\link[=func]{func()}}
[pkg::func()]
func() in the pkg
\code{\link[pkg:func]{pkg::func()}}
[thing]
topic in this package
\link{thing}
[pkg::thing]
topic in the pkg
\link[pkg:thing]{pkg::thing}
[`thing`]
topic in this package
\code{\link{thing}}
[`pkg::thing`]
topic in the pkg
\code{\link[pkg:thing]{pkg::thing}}
Remember to put Roxygen: list(markdown = TRUE) in the DESCRIPTION
Markdown shortcodes available from roxygen2>=6.0.0
In addition to the answer by potockan:
Some packages document several functions in a single help page. For example, the trim function from Bioconductor package GenomicRanges is documented in intra-range-methods (which is also the name of a help page from other packages such as IRanges).
To link to the right page with roxygen2 you can use:
\link[GenomicRanges:intra-range-methods]{trim}
or
\code{\link[GenomicRanges:intra-range-methods]{trim}}
to format the text correctly.
The help page will only show trim but will link to the right help page.
To link to a function, we slightly abuse markdown syntax by using [function()] or [pkg::function()].
Re-document your package by pressing Cmd/Ctrl + Shift + D.
Build and install your package by clicking in the build pane or by pressing Ctrl/Cmd + Shift + B. This installs it in your regular library, then restarts R and reloads your package.
Preview documentation with ?

Need the filename of the Rnw when knitr runs in rStudio

When working on a reproducible research project, I would like to know the name of the Rnw file that is being run to use as an R variable.
This would be analogous to inserting an MSExcel filename in a footer
I am using RStudio Server on Ubuntu.
Thank you.
knitr now has a method for this: current_input()
https://github.com/yihui/knitr/issues/701
You can use the following two idioms to fetch the directory and name of the current file in knitr:
knitr:::.knitEnv$input.dir
knitr:::knit_concord$get("infile")
This is independent of RStudio, the knitr package is entirely responsible for this. These are private functions and variables that can change at any time without notice, so if you need something reliable, you might want to file an issue on GitHub.

Rstudio editor snippets

Does Rstudio have a mechanism to configure snippets of code, like Geany for example? For faster writing whole sections of user predefined frequent code.
It is not exactly the same as TAB completion already built in rstudio.
Example by mimicking geany snippets
While snippet definition is like line below:
fun = %cursor% <- function(x, ...)\s{\n\n}\n
the usage is like this:
fun<TAB> (like bash style completion)
# will end up in following insertion:
<- function(x, ...) {
}
so the user can then faster write the code by using her own snippets definition. And user can define ANY snippet of any size for completion by TAB.
It is not the Rstudio extract cmd, nieder Rstudio existing TAB context browser.
Code snippets are available in RStudio version 0.99.
https://support.rstudio.com/hc/en-us/articles/204463668-Code-Snippets
The "Extract Function" feature in RStudio may be what you're looking for. Scroll down to the Extract Function section and accompanying screenshot on this page of rstudio.com's documentation: http://www.rstudio.com/ide/docs/using/source
The text of the section reads, "RStudio can analyze a selection of code from within the source editor and automatically convert it into a re-usable function. Any 'free' variables within the selection (objects that are referenced but not created within the selection) are converted into function arguments."
Also see this screenshot: http://www.rstudio.com/images/screenshots/rstudio-code-transform.png
I do not know of such functionality. However, if you want to quickly want to implement functionality with small changes you could also achieve this using functions.
Ok, your question is now clear to me. To my knowledge, Rstudio currently does not have this kind of functionality. You could, however, post a request on their forum for this feature. They respond quite actively to these kinds of requests, so you could give it a try.

Sweave syntax highlighting in output

Has anyone managed to get color syntax-highlighting working in the output of Sweave documents? I've been able to customize the output style by adding boxes, etc. in the Sweave.sty file as follows:
\DefineVerbatimEnvironment{Sinput}{Verbatim}{fontseries=bc,frame=single}
\DefineVerbatimEnvironment{Soutput}{Verbatim}{frame=leftline}
\DefineVerbatimEnvironment{Scode}{Verbatim}{fontseries=bc}
And I can get the minted package to do syntax highlighting of verbatim-code blocks in my document like so:
\begin{minted}{perl}
use Foo::Bar;
...
\end{minted}
but I'm not sure how to combine the two for R input sections. I tried the following:
\DefineVerbatimEnvironment{Sinput}{minted}{r}
\DefineVerbatimEnvironment{Scode}{minted}{r}
Any suggestions?
Yes, look at some of the vignettes for Rcpp as for example (to pick just one) the Rcpp-FAQ pdf.
We use the highlight by Romain which itself can farm out to the hightlight binary by Andre Simon. It makes everything a little more involved---Makefiles for the vignettes etc pp---but we get colourful output from R and C/C++ code. Which makes it worth it.
I have a solution that has worked for me, I have not tried it on any other systems though so things may not work out of the box for you. I've posted some code at https://gist.github.com/797478 that is a set of modified Rweave driver functions that make use of minted blocks instead of verbatim blocks.
To use this driver just specify it when calling the Sweave function with the driver=RweaveLatexMinted() option.
Here's how I've ended up solving it, starting from #daroczig's suggestion.
\usepackage{minted}
\renewenvironment{Sinput}{\minted[frame=single]{r}}{\endminted}
\DefineVerbatimEnvironment{Soutput}{Verbatim}{frame=leftline}
\DefineVerbatimEnvironment{Scode}{Verbatim}{}
While I was at it, I needed to get caching working because I'm using large data sets and one chunk was taking around 3 minutes to complete. So I wrote this zsh shell function to process an .Rnw file with caching:
function sweaveCache() {
Rscript -e "library(cacheSweave); setCacheDir(getwd()); Sweave('$1.Rnw', driver = cacheSweaveDriver)" &&
pdflatex --shell-escape $1.tex &&
open $1.pdf
}
Now I just do sweaveCache myFile and I get the result opened in Preview (on OS X).
This topic on tex.StackExchange might be interesting for you, as it suggest loading the SweaveListingUtils package in R for easy solution.

Resources