rstudio code folding like in matlab GUI - r

I normally use matlab GUI for programming and it has very nice code folding features, such as the following:
%% This is one chunk of code I can fold just because I am using the %% comment format.
matrix = [1 2 3; 4 5 6];
vector = [1 2];
ax = vector*matrix;
%% This is another chunk of code I can fold because I am using the %% comment format.
matrix2 = [7 8 9; 10 11 12];
vector2 = [7 8];
ax2 = vector2*matrix2;
As mentioned in the matlab code, the %% comment will immediatly give the matlab GUI the folding option and a plus/minus sign for unfolding/folding will appear on that line with the comment visible.
Is it anyway to achieve such formatting in rstudio or a good R gui?
I'd like to have the plus/minus feature, and the fact that the first line comment is visible so I can know what's in the folded chunk of code.
Thanks.
Photos of the GUI minus/plus unfolded/folded attached bellow:
When I try the same approach in RStudio, seems that the only option is edit -> folding collapse/expand but it hides the comments, and its not as automatable as the %% feature. In my case is more of a problem because I use X11 so I do not want to have to go to edit -> folding... all the time, but rather automate as in matlab using %%.

Have you seen the code folding section of the RStudio documentation? Everything you ask for is described therein.
To directly quote the most relevant section of the documentation, you can create a code section on any comment line by including at least four trailing dashes (-), equal signs (=), or pound signs (#) automatically creates a code section.
If that wasn't clear enough, maybe we can learn by example:
# Section One ---------------------------------
# Section Two =================================
### Section Three #############################
To illustrate that this actually works further, please examine the following two screenshots. If you are getting something different, I suggest you update RStudio and then follow up directly with the good folks at RStudio:
Expanded:
Collapsed:

Related

Folding selected text

I like that in Atom text editor, you can hide code blocks to get a better overview. This is called Folding and is described here. There it says:
Finally, you can fold arbitrary sections of your code or text by making a selection and then typing Alt+Ctrl+F or choosing "Fold Selection" in the Command Palette.
I would like to make use of this, but it doesn't work for me. (I select a section of my code, then press the combination Alt+Ctrl+F, but nothing happens.) My operating system is Linux Mint 20.2 and the Atom version is 1.58.0.
I am looking for a fix or for a different method to fold selected text.
My use-case right now would be to fold Python docstrings. So if someone knows how to accomplish only that in Atom, you would also help me.
Although I did not find out why the hotkey doesn't work, I found a solution that fits my needs. The Atom package custom-folds adds the functionality to define regions that may be folded.
After installing custom-folds, I added the lines #<editor-folds and #</editor-fold> at the beginning and end of the docstring, respectively:
def average(a, b):
#<editor-fold
"""
Return the mean value of inputs a and b
"""
#</editor-fold>
return (a+b)/2
The commands #<editor-fold and #</editor-fold> are recognized and highlighted; also, a dropdown arrow appears where the code region can be folded or unfolded.

Move cursor up/down one line in Atom

I'm using Atom with soft wrap turned on. In most simple editors such as gedit, Ctrl-Down would be used to skip ahead to the true next line, ignoring any wrapped lines below (same as j and k in Vim).
However in Atom this shortcut produces the result of moving the line itself around, which is less useful to me. I'd like to remap Ctrl-Up and Ctrl-Down to move the cursor up or down to the next true line, as described above.
I'm familiar with editing my keymap file, but I simply can't find any command that would be the equivalent of moving ahead one full line.
You could write a custom command in your init.coffee like this:
atom.workspaceView.command 'custom:move-next-buffer-line', ->
editor = atom.workspace.getActiveEditor()
editor.moveCursorToEndOfLine()
editor.moveCursorRight()
And then just reverse it for moving to the previous buffer line. You can then map the custom command in your keymap, which you said you're familiar with.
If you're using the vim-mode-plus package, then just modify your keymap.cson file by adding
# except insert
# -------------------------
'atom-text-editor.vim-mode-plus:not(.insert-mode)':
# Motions
# -------------------------
'k': 'vim-mode-plus:move-up-screen'
'j': 'vim-mode-plus:move-down-screen'
See for details https://github.com/t9md/atom-vim-mode-plus/blob/master/keymaps/vim-mode-plus.cson

Multiline Comment Workarounds?

I (sort of) already know the answer to this question. But I figured it is one that gets asked so frequently on the R Users list, that there should be one solid good answer. To the best of my knowledge there is no multiline comment functionality in R. So, does anyone have any good workarounds?
While quite a bit of work in R usually involves interactive sessions (which casts doubt on the need for multiline comments), there are times when I've had to send scripts to colleagues and classmates, much of which involves nontrivial blocks of code. And for people coming from other languages it is a fairly natural question.
In the past I've used quotes. Since strings support linebreaks, running an R script with
"
Here's my multiline comment.
"
a <- 10
rocknroll.lm <- lm(blah blah blah)
...
works fine. Does anyone have a better solution?
You can do this easily in RStudio:
select the code and click CTR+SHIFT+C
to comment/uncomment code.
This does come up on the mailing list fairly regularly, see for example this recent thread on r-help. The consensus answer usually is the one shown above: that given that the language has no direct support, you have to either
work with an editor that has region-to-comment commands, and most advanced R editors do
use the if (FALSE) constructs suggested earlier but note that it still requires complete parsing and must hence be syntactically correct
A neat trick for RStudio I've just discovered is to use #' as this creates an self-expanding comment section (when you return to new line from such a line or insert new lines into such a section it is automatically comment).
[Update] Based on comments.
# An empty function for Comments
Comment <- function(`#Comments`) {invisible()}
#### Comments ####
Comment( `
# Put anything in here except back-ticks.
api_idea <- function() {
return TRUE
}
# Just to show api_idea isn't really there...
print( api_idea )
`)
####
#### Code. ####
foo <- function() {
print( "The above did not evaluate!")
}
foo()
[Original Answer]
Here's another way... check out the pic at the bottom. Cut and paste the code block into RStudio.
Multiline comments that make using an IDE more effective are a "Good Thing", most IDEs or simple editors don't have highlighting of text within simple commented -out blocks; though some authors have taken the time to ensure parsing within here-strings. With R we don't have multi-line comments or here-strings either, but using invisible expressions in RStudio gives all that goodness.
As long as there aren't any backticks in the section desired to be used for a multiline comments, here-strings, or non-executed comment blocks then this might be something worth-while.
#### Intro Notes & Comments ####
invisible( expression( `
{ <= put the brace here to reset the auto indenting...
Base <- function()
{ <^~~~~~~~~~~~~~~~ Use the function as a header and nesting marker for the comments
that show up in the jump-menu.
--->8---
}
External <- function()
{
If we used a function similar to:
api_idea <- function() {
some_api_example <- function( nested ) {
stopifnot( some required check here )
}
print("Cut and paste this into RStudio to see the code-chunk quick-jump structure.")
return converted object
}
#### Code. ####
^~~~~~~~~~~~~~~~~~~~~~~~~~ <= Notice that this comment section isnt in the jump menu!
Putting an apostrophe in isn't causes RStudio to parse as text
and needs to be matched prior to nested structure working again.
api_idea2 <- function() {
} # That isn't in the jump-menu, but the one below is...
api_idea3 <- function() {
}
}
# Just to show api_idea isn't really there...
print( api_idea )
}`) )
####
#### Code. ####
foo <- function() {
print( "The above did not evaluate and cause an error!")
}
foo()
## [1] "The above did not evaluate and cause an error!"
And here's the pic...
I can think of two options. The first option is to use an editor that allows to block comment and uncomment (eg. Eclipse). The second option is to use an if statement. But that will only allow you to 'comment' correct R syntax. Hence a good editor is the prefered workaround.
if(FALSE){
#everything in this case is not executed
}
If find it incredible that any language would not cater for this.
This is probably the cleanest workaround:
anything="
first comment line
second comment line
"
Apart from using the overkilled way to comment multi-line codes just by installing RStudio, you can use Notepad++ as it supports the syntax highlighting of R
(Select multi-lines) -> Edit -> Comment/Uncomment -> Toggle Block Comment
Note that you need to save the code as a .R source first (highlighted in red)
I use vim to edit the R script.
Let's say the R script is test.R, containing say "Line 1", "Line 2", and "Line 3" on 3 separate lines.
I open test.R on the command line with Vim by typing "vim test.R".
Then I go to the 1st line I want to comment out, type "Control-V", down arrow to the last line I want to comment out, type a capital I i.e. "I" for insert, type "# ", and then hit the Escape key to add "# " to every line that I selected by arrowing down. Save the file in Vim and then exit Vim by typing ":wq". Changes should show up in Rstudio.
To delete the comments in Vim, start at the first line on top of the character "#" you want to delete, again do "Control-V", and arrow down to the last line you want to delete a "#" from. Then type "dd". The "#" signs should be deleted.
There's seconds-worth of lag time between when changes to test.R in Vim are reflected in Rstudio.
Now there is a workaround, by using package ARTofR or bannerCommenter
Examples here:
In RStudio an easy way to do this is to write your comment and once you have used CTRL + Shift + C to comment your line of code, then use CTRL + SHIFT + / to reflow you comment onto multiple lines for ease of reading.
In RStudio you can use a pound sign and quote like this:
#' This is a comment
Now, every time you hit return you don't need to add the #', RStudio will automatically put that in for you.
Incidentally, for adding parameters and items that are returned, for standardization if you type an # symbol inside those comment strings, RStudio will automatically show you a list of codes associated with those comment parameters:
#' #param tracker_df Dataframe of limit names and limits
#' #param invoice_data Dataframe of invoice data
#' #return return_list List of scores for each limit and rejected invoice rows

Printing hard copies of code

I have to hand in a software project that requires either a paper or .pdf copy of all the code included.
One solution I have considered is grouping classes by context and doing a cat *.extension > out.txt to provide all the code, then by catting the final text files I should have a single text file that has classes grouped by context. This is not an ideal solution; there will be no page breaks.
Another idea I had was a shell script to inject latex page breaks in between files to be joined, this would be more acceptable. Although I'm not too adept at scripting or latex.
Are there any tools that will do this for me?
Take a look at enscript (or nenscript), which will convert to Postscript, render in columns, add headers/footers and perform syntax highlighting. If you want to print code in a presentable fashion, this works very nicely.
e.g. here's my setting (within a zsh function)
# -2 = 2 columns
# -G = fancy header
# -E = syntax filter
# -r = rotated (landscape)
# syntax is picked up from .enscriptrc / .enscript dir
enscript -2GrE $*
For a quick solution, see a2ps, followed by ps2pdf. For a nicer, more complex solution I would go for a simple script that puts each file in a LaTeX listings environment and combines the result.

Annuity or Angle Operation Symbol in LaTeX

How do I set the symbol for the angle or annuity operation in LaTeX? Specifically, this is the actuarial a angle s = (1-vs)/i.
I've looked at Life's Contingency's Package, various Actuarial Outpost forum threads, and the Comprehensive Symbol List for LaTeX, and combined the best into the following macros:
\DeclareRobustCommand{\lcroof}[1]{
\hbox{\vtop{\vbox{%
\hrule\kern 1pt\hbox{%
$\scriptstyle #1$%
\kern 1pt}}\kern1pt}%
\vrule\kern1pt}}
\DeclareRobustCommand{\angle}[1]{
_{\lcroof{#1}}}
You can then use this macro for the problem's example by typing
$a\angle{s}$
If you need a full set of actuarial symbols, you should use the Life's Contingency's Package lifecon. Using lifecon, you can set the above by typing
$a_{\lcroof{s}}$
For a very comprehensive list of LaTeX symbols, see The Comprehensive LaTeX Symbol List. Worth printing out and keeping under your pillow. Page 95 has some code that may do what you want.
I had the same problem with the actuarial symbol and the subscript/superscript, sooo I made a package to make my life easier and help other.
Plus, I’ve add some shortcut to save time.
The project page and the CTAN.
All you need is the actuarialsymbol package.
At the beginning of the code you have to write
\usepackage{actuarialsymbol}
For the sub/superscript
\actsymb['subscripLeft']['superscriptL']{<middle>}{'subscriptR'}{'superscriptR'}
Example of output:
Example of shortcut for actuarial symbol :
I've been doing some typesetting for a professor of mine and it turns out I needed some help producing the accumulated value of an annuity notation.
I asked this question on the tex stack exchange here
The result that Heiko Oberdiek produced was
\documentclass{article}
\usepackage{siunitx}
\makeatletter
\newcommand*{\NegationLike}[1]{%
\mathop{%
\mathpalette\#NegationLike{#1}%
}%
% A little space is added automatically,
% if a math ord atom follows.
}
\newdimen\BarLineWidth
\newcommand*{\#NegationLike}[2]{%
% #1: math style
% #2: argument
\vbox{%
% The rule thickness of \overline or \underline
% is available in the font dimen register 8
% of the math family 3 of the current size.
\BarLineWidth=%
\the\fontdimen8%
\ifx\displaystyle#1\textfont
\else\ifx\textstyle#1\textfont
\else\ifx\scriptstyle#1\scriptfont
\else\scriptscriptfont
\fi\fi\fi
3\relax
% The rule at the top
\hrule height\BarLineWidth
% Move the box with the vertical line
% as height as the top of the upper line
% to get a better corner.
Which produces:
accumulated value of annuity
\annu
A good list of latex symbols can be found here http://www.ctan.org/tex-archive/info/symbols/comprehensive/symbols-a4.pdf

Resources