How exactly do I comment R? - 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

Related

How to get roxygen2 to interpret backticks as code formatting?

The standard way of writing documentation with code formatting is by using \code{}.
That is, #' #param foo value passed on to \code{bar()} becomes
Arguments
foo    value passed on to bar()
However, I've seen some packages (i.e. dplyr) using backticks instead of \code{} to the same effect. This is much better, since it's less clunky and allows for very nice syntax highlighting.
However, if I try that on my own package, the backticks get interpreted as... just backticks, like any other character.
The documentation for dplyr::across(), for example, starts with:
#' #description
#' `across()` makes it easy to apply the same transformation to multiple [...]
which gets compiled and displayed in the man page as:
Description
across() makes it easy to apply the same transformation to multiple [...]
But if I try something similar on my package, I get:
Description
`across()` makes it easy to apply the same transformation to multiple [...]
Weirdly, I've forked the package glue (which also manages to use backticks for code formatting) for a simple PR, and if I build the package locally, the backticks work (I get code formatting). Can't for the life of me figure out why it works there but not for my package.
So, is there some setting I need to modify to get this to work? I checked the dplyr.Rproj but found nothing relevant. I also glanced at the Doxyfile, but didn't know what it did or what I'd even be looking for there.
All credit goes to #rawr's comment to the question, just formalizing it with an answer:
The secret is in the roxygen2 documentation: just add the following to the end of the package DESCRIPTION file:
# DESCRIPTION file
# [... rest of file ...]
Roxygen: list(markdown = TRUE)
RoxygenNote: 7.1.2 # actually works since 6.0.0
As that code would imply, this sets roxygen2 to interpret the commands as good ol' Markdown like we're used to using here on SO and elsewhere. This also implies all the other standard Markdown commands such as **bold** and *italics*, as well as [text](http://www.url.com), code blocks defined by ```, itemized and enumerated lists, etc. It's a huge improvement across the board.
Though be careful and take a look at the documentation, since there are a few gotchas. For instance, an empty line isn't necessary to start lists, so don't start any lines with #' 1. [...] or #' * [...] or you'll accidentally create a list!). There's also a few things which don't work yet, but they're pretty minor.

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.

Xaringan: Math renders as inline code in footnote class

Using the default Xaringan CSS, if $math$ is placed in a footnote, it appears to be rendered as inline code, rather than rendering as math. I was not able to find information about this - is this just a natural limitation in Xaringan or remark.js? Or perhaps I am doing something wrong?
See basic example below:
# A Test
- This is a test<sup>1</sup>
.footnote[<sup>1</sup> This includes $\delta+\frac{2}{3}$ math.]
This will render the math between the $$ as if it were between backticks.
[UPDATE 17/12/2019] Another way to circumvent this is to replace the maths expression $\delta+\frac{2}{3}$ with \(\delta+\frac{2}{3}\) which bypasses any need for remark.js to convert $ and thus avoiding the bug there.
Yes I noticed this too. I think somehow remark.js is interfering with mathjax but I don't really know. To get around this I use the html code directly instead. So below should work:
# A Test
- This is a test<sup>1</sup>
<span class="footnote"><sup>1</sup> This includes $\delta+\frac{2}{3}$ math.</span>
[UPDATE]
The explanation of why this happens can be found here. TL;DR: remark.js removes the brackets necessary for mathjax to detect the maths.
Yihui also provided an alternate hack if the use of .footnote[] is desirable which involves adding the brackets to the inline math code:
.footnote[<sup>1</sup> This includes `\\(\delta+\frac{2}{3}\\)` math.]

Indenting code within .R script without using a function

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

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?

Resources