Different Colored Comments - r

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.

Related

How to suppress the carriage return mathjaxr adds when `mjeqn` starts a line?

If I begin a line (i.e. a paragraph) in the details section of my .Rd file with \mjeqn a new line immediately follows the expression (anti-bonus points: the added new line seems to have wider line spacing than 'ordinary' new lines). How can I suppress this behavior when I want to start a line with inline mathy stuff using \mjeqn?
Sketched out example:
\mjeqn{foo^{bar}}{foo^bar} estimates bas.
Gives me something like the below when parsed (into html preview):
foo^bar
estimates bas.
I am just using mathjaxr, not roxygen2.
I don't know why that happens, but it looks like a bug, maybe in the R help rendering engine, maybe in the mathjaxr macro, or maybe in MathJax. A simple workaround is to put something invisible on the line ahead of the math, e.g.
\emph{}\mjeqn{foo^{bar}}{foo^bar} estimates bas.
Edited to add:
Digging into the rendering code, it seems the problem is that the \mjeqn macro expands into something that R ignores when trying to determine paragraphs, so it thinks the paragraph starts after that. Putting \emph{} ahead of it tells R that the paragraph has started and everything is fine. This has been incorporated into the package, so if you download the Github version, or wait for the next CRAN release, you won't need the workaround.

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

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?

How to disable spell checking in code regions in RMD files (Markdown, knitr, R)

I am using the Vim-R-plugin to edit files containing markdown and R-code blocks such that the files can be complied using knitr. The filetype is: RMD. I have enabled spell checking. How can I disable the spell checking within the code blocks?
Spell checking is attached to certain syntax groups. Find the :syn region that covers the R code blocks, and append / edit in contains=#NoSpell.
Instead of trying to get the #NoSpell working by region, my approach is to toggle between languages.
I work in three languages which are set up to toggle with a function key where I include "nospell". This makes turning spellchecking on and off as easy as pressingt F7. When coding and writing nospell is turned on, when finalizing the edits I toggle to the appropriate language.
In fact, I find spellchecks in my code to be a plus. I make mistakes in the comment sections too, sometimes even in variable names/plot lables etc. This way you have a quick last check of all language items that are going to be visible .
I got this to work on OS X by editing the ~/.vim/syntax/R.vim and doing a search and replace of all instances of #Spell to #NoSpell. Then restarting vim. All the red underscores were gone from the code chunks but were still in the rest of the the rmarkdown.
Interestingly this has not effected the spell checking in pure R documents that have a .R extension, so I having thought I understood what I was doing perhaps I have to admit I don't fully. But at least it has turned off spell checking of the code chunks in rmarkdown (Rmd) documents while leaving it still working elsewhere in the document.

Resources