Indenting code within .R script without using a function - r

I am new to R, and despite searching the forums I have been unable to find a solution to indenting code within both the Source window and Document Outline (Ctrl+Shift+O).
An example is shown below.
Ideally, I would want the code to function as below when pressing Alt+O
This function does seem to be implemented in some fashion as you get the indented code with functions but this is less than ideal.
# Section 1 -----------------------------------------------------------
function(x) {
# Section 1A ===========================================================
}
Has anyone found a work-around to implement this?

Not a fix but a workaround:
Any whitespace after a "." is included in the heading, so a "." followed by a tab or space can be used to create indented headers preceded by a ".".
# Section title ---------------------------------------------------------------
# . Subsection A --------------------------------------------------------------
# . . A.1 ---------------------------------------------------------------------
Would still be nice to see this implemented the way it is in R markdown, but in the mean time might make it easier to navigate scripts using sub-headers.
Screenshot of example script using dot-tab to indent headers

For what it's worth, this sort of nested indent is implemented for Markdown sections (for e.g. R Markdown documents), e.g.
However, this sort of nested is not implemented for sections in plain R scripts. You might consider filing this as a feature request for the RStudio team.

Thanks #Foztarz I posted this as an issue about a year ago on the GitHub. They claimed it was a worthy enhancement but they keep pushing it to the next version of RStudio lol. My work-around was similar. I used Alt codes to insert symbols I found a bit more visually appealing over .
# ▬ Section A ------
# ▐ ▬ Section A.1-----------
Here's what it looks like inside RStudio

Two additions:
Box-drawing characters look much better than the characters mentioned in https://stackoverflow.com/a/63812437/13776976 #Patricks answer
From RStudio 1.4 on, you can indicate sub-sections by additional '#' at the start of the line, see RStudio How To Article

Related

Different Colored Comments

Simple question about comment code aesthetics (color):
I recently noticed in someone's comment code that part of their comment color changed while using the # symbol. After experimenting with it, I noticed you also need to have an apostrophe (') right after the octothorp (#) as such:
#' #text
^--- This turned orange!
Since I'm a detailed commenter, I'd love to step things up if I could by adding color to my comments. I know part of the reason is my global IDE (RStudio) options, but I'd never seen anything change a comment's color before, so I was just curious:
Why does this occur? I've only seen # used when handling large, more-complex objects that need further specification => Ex. LargeObject#data$variable
Are there other symbols that trigger a color change? There's quotes of course (""), but quotes do not change color when they're commented out with an octothorp (#).
Also, on the image (bottom row), is there possibly a way to start and end a comment, followed by a command, all on one line? => Ex. #comment# print(summary(df))
The special highlighting you're seeing — words being highlighted after #' # — is specific to roxygen markup (a documentation-generation system for R). I don't know why that category doesn't seem to be listed/themeable (see #2).
The RStudio syntax highlighting colours are customizable (you can edit these themes visually), but based on what's documented at the link, there appears to be only one category for "comments".
This question has to do with the R parser, not the RStudio highlighting system. So the answer is "no"; everything from the first # on a line to the line break is considered a comment, no exceptions. In principle you could adjust the RStudio highlighting engine to recognize various delimiters within comments and display material following them differently, but you can't create in-line comments (as you could with /* */ in C) without modifying the R parser.

How exactly do I comment R?

I apologize if this sounds stupid. I am someone who tries my best to make my code reproducible and understandable. So I took the idea "make useful comments" and "comment every line of code"
Is there another way to comment code besides this mess that like the previous post mentioned:
Here is a simulated reproduceable using a simple lines of code and tidyverse. For this example please pretend, that library(package) is the most complicated code you have seen.
# this a comment
## this is a tabbed comment
library(tidyverse) # this is an inline comment
But what if you commented that out.
# this a comment
library(ggplot2) # this is an inline comment
# library(tidyverse) This is commented code
Now you have something is hard to understand. Which is the comment and which is the code?
I wish there was a way in the syntax to add another character to help distinguish my comments and comment out code.
I agree with many the answers on the link you referenced Commenting R. Commenting in R starts with a # and block comments are not supported.
Having said that, you could make your own scheme. As long as your comment line starts with a #, you can follow it with anything
You could make your own schema to visually allow you to tell where commented code is vs actual comments
If you used something like:
####### This is an actual comment
or
##<---- Comment This is also a comment ---->
or
######################
## Fancy comment for the next series of code lines
## More comements
## More verbose comments
######################
or like Roxygen2 comments from the above liniked comment. Roxygen2 Roxygen2 documentation with schema for comments uses a predefined schema of #':
#' roxygen2 Comments
#' roxygen2 Comments2
You could visually see the difference. Additionally, you could search for ## or #' to find actual comments and search for # (hash with a space) to find commented code.
This is in danger of getting opinion-based answers, but I'll try to give an objective answer.
Without serious hacking, you won't be able to change the parser to add an additional comment character
when I have commented-out lines with comments, I usually add an additional set of comment characters:
# library(tidyverse) ## This is commented code
This way if I uncomment the line, the comment stays commented.
some programming interfaces (such as Emacs) distinguish between the meanings/default indentation of different numbers of hash characters: single hash (#) gets indented to a standard comment depth, double (##) gets indented to the current code indentation level, and three or more (###) gets set to the beginning of the line. You could adopt a convention for yourself similar to this. (Similarly, anything you include after a hash is ignored, so you could decide for yourself that #* ... represented a "real" character)
some people consider it bad practice, but as discussed here if you delimit a code block with if (FALSE) { ... }, it won't get executed (although it does need to be syntactically valid code, which isn't required for commented material

RStudio: Code sections and compiled notebooks

I really like RStudio's code sections because they help me keep my code organized and makes navigation very easy. So, the code/comment line for code sections look like this (the key for RStudio to recognize the code section is that the comment should end with four or more #, - or =).
# Section One ---------------------------------
# Section Two =================================
### Section Three #############################
Now, I also find very useful "Compiling Notebooks from R Scripts" because you can produce reports directly from your script (which I find much more comfortable working with) without having to write an RMarkdown document. You simply have to use roxygen2-style comments (using #' as prefix) and they will be converted to markdown and/or use #+ or #- prefixes to control RMarkdown chunk options.
Now, I want the best of both worlds but I cannot find a way to get it. I want to have code sections (recognizable for RStudio) in the report (with the proper markdown for headings #, but without the extra #### at the end of the line). Seems like an impossible task to me. If I use #' prefix, I get the section in the report but RStudio does not recognize it as a code section. If I do not use roxygen2-style comments, RStudio recognizes the code section but it does not appear in the report (ok, it appears but as an ugly comment in the formatted code). The best solution I have found so far is to use the #+ prefix and simulate a code chunk label. That way I can get RStudio to recognize it as a code section, and it does not appear in the report as an ugly comment.
Any ideas on how to do this better?

Hide and show comments

I'm writing all my scripts on .R file using R for mac. It is convenient to me because there are colors to highlight the type of commands.
I have a many comments following the # symbol that are useful when I forget about the meaning of my script but they tend to blur my script so that it gets harder to find a given command line.
Is there a way to hide and show these comments ? (Using the programm I'm currently using or another one). What would you suggest as the best program to write R script ?
Thanks a lot !
RStudio supports code folding. You can standardize your comment blocks so that they are recognized as code blocks.
For example, enter this into your RStudio editor
#=======================================================
# this is a comment block
# more comments here
# comments upon comments
and then press Alt+L to fold, and Alt+Shift+L to unfold.
Try RStudio for mac. One of the greatest code writing environment for R there is.
You can also try Emacs, which is more like old-fashioned command line editor. You can find a good guide here.

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