sc73
sc73

Reputation: 135

Shortcut for running a single line of code in R

Does anyone know how I could create a keyboard shortcut or something similar to run a single line of diagnostic code in R Studio? i.e. if I wanted to do something simple, like checking the dimensions of a data frame, but I wanted to do it a lot throughout the day and didn't want to be continually typing dim(data), how could I get dim(data) into a keyboard shortcut or some other quick easy way to call that single line of code?

Upvotes: 2

Views: 3592

Answers (3)

Spacedman
Spacedman

Reputation: 94317

The plain R terminal has a reverse incremental search function to make repetitive things easy. Hit Ctrl-R and start typing, it will match against your history. In this example, I've typed "di" and its enough to find the last "dim" call I did:

> x=matrix(1:12,3,4)
> dim(x)
[1] 3 4
> y=runif(100)
> dim(x)
[1] 3 4
# hit Ctrl-R at the prompt and type "d"... "i"....
(reverse-i-search)`di': dim(x)

I can hit return now, and it will do dim(x) for me. In fact it found it at the "d" because there was nothing else starting with a "d!" in the history.

There's a similar things in Emacs-ESS but I don't suppose you are using that. I don't know if this is implemented in RStudio, StatET, Architect, RCmdr or any of the other R interfaces that you might be using. I think RStudio might have a quick history search.

Upvotes: 3

Adam Spannbauer
Adam Spannbauer

Reputation: 2757

You could try using the snippet feature in RStudio (Tools -> Global Options... brings up the menu below). You can then add a snippet such as the code chunk below.

snippet d
   dim(data)

Once the snippet is saved you can type the d (or whatever other string you defined after snippet). Then press tab and RStudio will give you the option to replace the shortcut string with the code listed in the snippet (here dim(data)).

There might be other options but for something as simple as a dim statement. There would likely be more effort than value add.

enter image description here

Upvotes: 2

Konrad Rudolph
Konrad Rudolph

Reputation: 546123

R itself can’d do that. Your editor may be able to, though (I know that Vim + Vim-R can do something like this).

What you can do in R is bind a function to an active binding. That way, whenever you invoke the binding, it executes your piece of code. To illustrate:

makeActiveBinding('x', function () dim(data), globalenv())

Now whenever you enter x in the R console, it executes dim(data).

Upvotes: 7

Related Questions