Hide and show comments - r

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.

Related

Create macros/shortcuts in R(studio)

Is there a way to write your own macro in R(studio). Many times in my code i need to comment out a line/piece of code, run it, and then comment it in again.
I know that a shortcut to comment in a line/piece of code is ctrl+shift+c, so I would like to create a shortcut e.g. ctrl+alt+c to comment in/out+run+comment in/out
You can create an Addins doing exactly what you want and assign a shortcut to it.
For exemple, that Addin is used to create upgraded shortcut for pipe.
To do what you want, a solution may be possible but require a few constrain.
Three, at least:
First, you need to select the code you want to comment
Secondly, in the same time you use the shortcut, the file should be saved.
Thirdly in your file, you can't have two time the same selected piece of code.
The commented code will be the input of the Addins.
The code is as simple as read your file, replace the code by commented code, then run the modified code.
It is different in what you want to achieve in the sense of in that case, it is more create a temporary copy of the code, comment the undesirable code, run the temporary modified code.
For shortcuts see here. Macros might be found here.
E.g. commenting in/out = Ctrl +Shift + C (Both)
If you want a to have a new shortcut, you have to ask RStudio. For an example, where it was already solved, see here. From the list of available shortcuts it is clear that "your" shortcut does not exist.

Print with syntax color in R-Studio

In R I always like to print out the script since it gives a good overview and one can adjust eventual errors. I like the syntax highlighting in R-Studio because it facilitates reading and fast comprehension of code.
Is there a way to print out the text with the highlighting I see in the editor?
Its not an R-Studio solution, but notepad++ will print R source with syntax highlighting.
RStudio will not print in colour, but it's easy to save the code as a PDF; in this case the syntax format is preserved. My favourite package is knitr.
library(knitr)
stitch("file_name.R")
The default output is PDF/Markup in .tex. If you prefer not to typeset, running the below will export as .html
stitch(script="file_name.R", system.file("misc", "knitr-template.Rhtml", package="knitr"))
Brief explanation
The reason this is an answer to this question in because of the last line of the question:
Is there a way to print out the text with the highlighting I see in
the editor?
so we are not limited to only and only using Rstudio software here.
After exploring the awesome answer by #rrg and realizing that it runs the code line by line, I wrote a comment below his answer and continued googling. My problem is that the code I wrote is so large and so time consuming to run that running it for the sake of having a syntax highlighted version is not feasible.
Most of the solution out there online involves having notepad++ which is a Windows application and I'm a dedicated Linux user, so I searched for a way I can do this in Linux (and possibly Mac)
The way I solved it:
Inspired by a blog post, I used the famous and beloved Vim to convert R to syntax highlighted HTML and then because you can open HTML in your browser, you can what ever you want with it (print, screenshot, etc.)
Activate synax highlighting in Vim:
open terminal
then open the vim config file by typing vim ~/.vimrc
press i from keyboard to go to "insert mode"
go to the end of the file using arrow keys on your keyboard
type syntax on at the end of the file
now you need to save and exit. For this you need to press Esc button from keyboard to come out of "insert mode" and then type :x and press Enter to save and close the file.
if you want to change the color scheme of the syntax highlighting, visit the bottom part of this website
From terminal open your file with Vim:
vim YOUR_FILE_PATH
Having you R code open in vim, you can turn on the line numbers if you like by pressing Esc and then write :set number and press Enter.
For converting R to HTML, press Esc to make sure you are not in "insert mode" and then type :TOhtml and press Enter. This will result is having a split window in terminal, half is your R code and the other half id your new HTML code.
For saving the files, type :x along with Enter button from keyboard twice to save both files (your R file will be unchanged if you have not typed anything extra in it and your HTML file will be created with the same name near your R code)
Now open it with your favorite browser (in my case Vivaldi) and do what ever you want (in my case converting the whole HTML into PNG)
Best way:
download https://github.com/jaredpetersen/codeprinter and paste in the r code. then choose syntax highlighting Xcode
For those using a Mac (and thus without access to Notepad++) cutting and pasting into Xcode and printing from there will also work.
As with Ron Jensen's earlier comment, this isn't an R Studio solution, but in the interests of "just getting it to work", I hope this helps someone.

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.

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