Rstudio editor snippets - r

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.

Related

Is it possible to interact with elements of the RStudio IDE itself using R code?

Is it possible to interact with the RStudio application using R code inside it? I mean interactions like opening a file in a card, creating a tab for a new unsaved file or changing some text inside an opened tab.
I know a very similar thing can be obtained by just simply creating a new text file or changing its content with R but this way it doesn't interact anyway with the RStudio app itself.
Some context: I was thinking of a tool that could automate inserting some reprexes / snippets of code which could work as a line of code that, when run from a file, replaces itself with a block of code or make a new unsaved file tab and put some code inside it. And yes, I know a very similar thing can be achieved other ways (e.g. simply copying the intended code block into the clipboard) but I'm curious and exploring the possibilities.
Thanks to the link provided by Konrad Rudolph I managed to find the answer myself.
There is a package called rstudioapi built into the RStudio that allows many different functionalities and doesn't require using plugins or addins.
All the features can be found in the official manual.
Opening a new unsaved file tab with some code in it can be obtained by running:
rstudioapi::documentNew(
"example code here",
type = "r",
position = rstudioapi::document_position(0, 0),
execute = FALSE
)
Inserting code can be easily done with insertText(text = "") which inserts text at the current position of the text cursor.
Changing one line into another can be obtained with the combination of getActiveDocumentContext(), which returns among others the document content and the selection range which is basically equivalent to the cursor position. Then the changing itself can be done with modifyRange() respectively to the cursor position and/or the document content.
That allows many possibilities including for example some smoother automation of the workflow.

customise R help files - font colouring

I'm wondering is it possible to customise R help files so that certain text is colour coded and easier to read. rdoc already does this except that it sends the output to the console. I would instead, like it to be sent to the help panel (i'm using Rstudio). Is there any workaround for this?
If we run ?lm normally, we can see the usual help file in the help panel on the right below but when you do it again after using rdoc in Rstudio we get the help file colour coded which is great but its sent to the console output (left side). Ideally, we would like it to remain on display in the help panel as we are running code. The way it is now - it disappears the minute you run something.
?lm
#devtools::install_github("mdequeljoe/rdoc")
library(rdoc)
options(rdoc.by_section = FALSE)
rdoc(lm)
I want to put the code into my .rprofile similar to #csgillespie .rprofile. Note, if you follow his code you can use ?lm instead of having to call rdoc(lm) directly to produce the colour coded console output.
I have a feeling this can't be done easily (if at all?) but interested to hear any suggestions.
Thanks
This is possible, but a little involved. You'll need your own css file defined to do it, though it would be possible to create a function that writes appropriate css.
As a proof of concept, I have used a copy of the "R.css" file defined inside every package's "/html" folder, and just changed the h2 color to red, with the file saved locally as "my.css".
Anyway, once you have the css file, this function will show the appropriate help file with the appropriate styling in your R viewer window:
help_css <- function(func, css_file)
{
pack <- sub("^.*:(.*)>$", "\\1", capture.output(environment(func)))
func <- deparse(substitute(func))
x <- readLines(paste0(find.package(pack), "/html/", func, ".html"))
x[3] <- paste("<style>",
paste(readLines(css_file), collapse = "\n"),
"</style>")
writeLines(x, file.path(tempdir(), "test.html"))
myViewer <- getOption("viewer")
myViewer(file.path(tempdir(), "test.html"))
}
So, for example, if I do:
help_css(lm, "my.css")
I get:
As of RStudio v1.2 you can style RStudio's integrated help pane by creating a custom user theme (essentially an .rstheme file).
I've given help pane styling a try in extending the rscodeio theme (without colored syntax highlighting, though). The latest CSS code is found here.
The help pane styling is currently only available in the optional Tomorrow Night Bright (rscodeio) editor theme.
To use it right away, you can either
install the current rscodeio master branch using remotes:
remotes::install_github("anthonynorth/rscodeio")
And then activating the editor theme named Tomorrow Night Bright (rscodeio) under Tools → Global Options… → Appearance → Editor theme. A first attempt of the help pane CSS code is included.
or – recommended – install my fork's interim-merge branch which contains all my latest work[1] overhauling the package, including a new apply_theme parameter to activate the desired editor theme right away:
remotes::install_github("salim-b/rscodeio#interim-merge")
rscodeio::install_themes(apply_theme = "Tomorrow Night Bright (rscodeio)")
[1]: This has also been proposed upstream a while ago (1, 2) but I haven't heard back from the author since.
The result looks as follows (example for ?pal::as_string):

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.

Saving R history from a particular session

I'm an instructor, and my students have expressed interest in a record of the code I run in class. Since this is often off-the-cuff, I would like to have an easy function I could run at the end of class which would save everything I had run in the session. I know savehistory() will save my entire history, but that is not what I'm looking for.
Similar to this question, except I believe I have a pedagogically sound reason for wanting the history, and I'm looking to limit what gets saved on a per-session basis, rather than on the basis of the number of lines.
I think if you invoke R with --no-restore-history (so that history from previous sessions isn't appended to the record for this one) and add
.Last <- function() {
if(interactive())
try(savehistory(paste0("~/.Rhistory_", sys.time())))
}
to your Rprofile, you should get self-contained, and timestamped history files every time R closes naturally.
The .Last function, when defined in the global environment, is called directly before normal close. See ?.Last
NB: this won't preserve your history in the case of a fatal error (crash) in R itself, though that shouldn't come up much in a teaching context.
NB2: the above code will have generated file names with spaces in them. Depending on your OS, this could range from no big deal to hairpulling nightmarescape. If it's a problem, wrap sys.time() with your favorite datetime formatting code, e.g. format(sys.time(), "<format string>") or something from lubridate (probably, I don't actually know as I don't use it myself).
In the development version of rite on GitHub (>= v0.3.6), you can use the sinkstart() function to dump all of your code, all of your results, or both to a little interactive Tcl/tk widget, from which you could then just copy or save the output.
To make it work you can do this:
devtools::install_github("leeper/rite")
library("rite")
sinkstart(print.eval = FALSE, prompt.echo = "", split = TRUE)
## any code here
sinkstop() # stop printing to the widget
That will look something like:
You can dynamically change what is printed in the widget from the context (right-click) menu on the widget. You can also dynamically switch between sinkstart() and sinkstop() if you only want some code and/or results output to there.
Full Disclosure: This is a package I developed.

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.

Resources