Shortcut for running a single line of code in R - 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?

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).

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.

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.

Related

don't echo to R console

Is there a way to turn off/on echoing to the R console (without using source()?)
For example, let's say I have a long .R script and I wish to run only one line from it. Say that line is x <- 9.
In RStudio, I can go to the line in question and use the "Run Selected Line(s)" command from the "Code" menu (or keyboard shortcut ctrl-enter on my PC). What'll happen upon doing that is it the console will print x <- 9 (and then obviously, R will create a variable called x and assign it the value 9).
Is there a way to not have this line echoed in the console (but still create the variable)?
The reason I ask is that I have lengthy lines of code that just define functions and every time I want to update a function, it echoes the whole thing to the console, and that burns a lot of time.
Thanks.

My attempt to use a "connection" while trying to read in input causes R to freeze or crash

Sorry, but the terminology I use in the title may not be used correctly. Whenever I try to run this code, it seems like it is trying to run it but never completes the command. When I click the stop command sign (red), it doesn't do anything. I cannot close out of R. So why is this taking forever to run?
con <- file('stdin', open = 'r')
inputs <- readLines(con)
When working in RStudio, you need to use readLines(stdin()) rather than readLines(file('stdin')), though you can use either if running R in the terminal.
However, there is also an issue from not specifying the number of lines of input since you are using RStudio. When reading input from stdin, Ctrl+D signals the end of input. However, if you are doing this from RStudio rather than from the terminal Ctrl+D is unavailable, so without specifying the lines of input there is no way to terminate the reading from stdin.
So, if you are running R from the terminal, your code will work, and you signal the end of input via Ctrl+D. If you must work from RStudio, you can still use readLines(stdin()) if you know the number of lines of input; e.g.,
> readLines(stdin(), n=2)
Hello
World
[1] "Hello" "World"
An alternate workaround is to use scan(), e.g.:
> scan(,'')
1: Hello
2: World
3:
Read 2 items
[1] "Hello" "World"
(On the third line I just pressed Enter to terminate input). The advantage there is that you don't need to know the number of lines of input beforehand.
RStudio has a somewhat indirect connection to R (At least 4 years ago it redirected stdin to nowhere). It is probably, for our purposes, embedded. This is probably part of why stdin() can work when paired with readLines (It creates a terminal connection rather than a file connection). #duckmayr's scan() solution is quite nice and is documented to be the kind of thing that works in this situation...
the name of a file to read data values from. If the specified file is
"", then input is taken from the keyboard (or whatever stdin() reads
if input is redirected or R is embedded).
In case you want to consider a blank input 'okay', you can also loop over getting the data from a single line with some sentinel value, i.e. thing that makes the loop stop (here 'EOF').
input <- function() {
entry <- ''
while (!any(entry == "EOF")) {
entry <- c(readline(), entry)
}
return(entry[-1])
}

How to make "buffered output" in R disabled by default?

When I work on the R console, I always want my results to be displayed instantly rather than buffered. Is there any method to turn buffered output off by default, so I don't need to press Ctrl + W every time I start the R console?
It definitely doesn't look like I'm the first one who encounters this, but surprisingly I can find nothing on this issue.
If you look in your R directory under etc, you should find a file called Rconsole, which contains a number of options that govern the behavior of the console. One of them is buffered = yes. Change yes to no and you should be all set.

RStudio does not display any output in console after entering code

The problem is that when I run the code, there's no return in the console; I mean it does run the code, but does not return any output.
For example, if I write
v <- c(1, 2, 3, 4, 5)
v
I would expect in return
[1] 1 2 3 4 5
But it's not working.
I have version RStudio Version 0.98.1079 and R Version 3.1.1
Possibility 1 (until the + sign was mentioned): I was wondering if you had been doing a tutorial where they were demonstrating the sink function and you hadn't gotten to the point where it was reversed.
> sink('out.txt') # diverts all output to a disk file
> v <- c(1,2)
> v # output went to file
> sink() # sets the output back to the console
> v
[1] 1 2
Another way would be to call closeAllConnections:
> sink('out.txt')
> v
> v
> closeAllConnections()
> v
[1] 1 2
Possibility 2: To address the lack of response with a "+" showing at the Rstudio console ... that is a sign that the R parser "thinks" the entered text has not completed a full R command. It may indicate that you haven't typed a closing bracket or parenthesis. If typing one or two of those is unsuccessful and you keep getting mor +'s then you may be successful with typing the [esc]-key. If it is showing up immediately after a restart then you should check your code for correctness and make sure that the .Rdata file is deleted from your working directory. If you don't know what that means then you may need to search for the methods appropriate to your operating system. You could also have an error in the code of one of your .rprofile files.
In any case these two possibilities have nothing to do with Rstudio per se and everything to to with the typical behavior of an R console session in pretty much any IDE.
Do the lines still start with a "+"? It is also possible you forgot to close the brackets of a function. Try "}".
I had the same issue and none of the tips mentioned here were working.
Session > Restart R did the trick for me, possibly suggesting that I had a similar problem as andrewH but was not patient enough to wait for R to behave again.
This is a very old question, but I just had the same problem with a different cause, so I thought I would describe it here case it should be useful to someone else. I was getting the regular command prompt, with nothing more, no matter what I typed at the command line. I tried multiple returns, escape, sink, traceback, closeAllConnections (which did give me a response, "error: unexpected ) in (), but then went back to the command prompt and ignored a second traceback).
Anyway after half an hour or so of pulling my hair out, up pops "View(Mid2)". Mid2 is a tibble with 8.5 million observations of 88 numeric variables. I must have tapped it in the environment pane accidentally. I suppose it just took that long for the viewer to render it. I assume that all the other things I did hit at once, because RStudio crashed immediately thereafter.
The interesting thing about this particular version of the problem is what didn't happen. The red stop sign in the upper right of the console window, that lights when R is busy, didn't light. That is unfortunate -- but understandable, if the RStudio viewer is a different process. But also, when my computer is working hard on a really big computation or IO task, the fan usually starts, but it didn't. Don't know why. . I took its absence, incorrectly, to mean no such computation was underway.
If the lines in console are starting with "+".
Save your work and close the 'RStudio' or other tool which you are using and Start it again, it worked for me.
If you are using R Studio Cloud, refresh or re-opening won't work.
Only clue from the above posts or answers is your console will always start with '+'
In my case I tried all possibilities of closing braces.
And ")" worked for me when I typed that into the console and press enter.
sink() function did nothing in R Studio Cloud
A simple mistake might have also caused this problem:
A rather lengthy command left abandoned in the console is blocking the appearance of the result line.
Thus, the console only shows that line, but the result from any code run from the source, will not appear.
To solve this, just switch to the console, remove any remaining command and try again.
Experiencing something like that explained here as an unresponsive console to the R-Code running was just devastating for me when I experienced it. But luckly although I tried every trick explained in this page, it did not work for me. At last I clicked on the "To console" option available just below the Environment, History, Connections, Tutorial Tab on the R Studio. It solved the puzzle for me just now.
The best solution I've found is closeAllConnections and/or sink which almost always work
But as a stop gap measure, View()'ing always works. It's sort of a pain but whatever you wanted to print out, surround by View and you can see it

Fix function in R for Ubuntu not working properly

I have been using R in the terminal window for Ubuntu. Recently I discovered the fix function in R, which I could use to edit my function. However, whenever I use the fix function, it opens up an editor (VIM) and I can use that to write my function. Then I type "wq" to save the work, however when I type the name of the function, it shows that there weren't any edits which were made to the function. Why does this happen?
In order to use the editing functionality, make sure you have either
the default editor installed (do eg grep EDITOR /etc/R/Renviron)
or set the EDITOR environment variable to a different editor you prefer,
or at runtime set options("editor"=....) to what you need.
Now, for the fix() function in particular, note this hint in its manual page:
‘fix’ invokes ‘edit’ on ‘x’ and then assigns the new (edited)
version of ‘x’ in the user's workspace.
So if the change "vanishes", maybe you were editing an object which is not yours. Start with something simple, edit it and see if that persists. Along the lines of
R> hw <- function() cat("Hello, world\n")
R> fix(hw) ## editing, adding 'new'
R> hw()
Hello, new world
R>

Resources