R/Rstudio Frustration - Can't Stop Code Execution - r

I often include View() statements in my R scripts. If I accidentally forget the closing bracket at the end of the line, and then run the line of code from the script window using ctrl-enter, R just keeps trying to execute the remainder of my script. I don't know why it does that (rather than using the + symbol to prompt me to provide further input).
Moreover, I've tried to stop this by setting break points in my code - I can click on the LHS of the page and a little red circle appears. But the breakpoints don't seem to work - R just ignores them and keeps going.
The only way I can get out of it is by killing the process in the Windows task manager and then going back in afterwards. But it's wasting a lot of time.
Does anyone know how I can fix this please?
Thank you.

In effect, what your function is processing looks like that:
... %>% View(
lm(am~cyl, mtcars)
...
...
As R can't find the bracket for ) it includes remaining statements as input to View and searches for the bracket.
Solutions
Kind of depends on what you want to do with those scripts but if the intention is to run them in the background consider using callr. This package lets you run R from R and offers kill methods to kill the process you started that way.
On Windows pressing Esc should enable you to get back to the console but if it's a memory intense process it may be difficult.
You may try pressing Ctrl+c in order to kill the process.

Related

How to stop taking input from standard input in rstudio

I actually want to take input from R in script mode (i.e. I'll copy and run the program written in an RScript) and I am using the readLines function for that (since I've come to know that readline function is meant to be used only in interactive mode). When I run the following code (in rstudio),
k = as.integer(readLines("stdin",n=1))
x = c()
it starts taking input, but the problem is that it doesn't stop taking input. Even if I click on the red octagon, it is not stopping and neither am I able to quit the session. I've to restart the computer. Any help on how can we stop it?? (I'll also be very happy if you suggest some better function to take and process input in script mode)

What exactly does Source on Save mean or do?

Despite numerous searches, I can't seem to find a clear explanation as to what "Source on Save" means in RStudio.
I have tried ?source and the explanation there isn't clear, either.
As far as I can tell, it seems to run the script when I hit Save, but I don't understand the relevance/significance of it.
In simple terms, what exactly does Source on Save do and why would/should I use it?
This is kind of a shortcut to save and execute your code. You type something, save the script and it will be automatically sourced.
Very useful for short scripts but very annoying for time consuming longer scripts.
So sourcing is basically running each line of your file.
EDIT:
SO thinking of a scenario where this might be useful...
You developing a function which you will later put into a package... So you write this function already in an extra file but execute the function for testing in the command line...
Normally, you have to execute the whole function again, when you changed something. While using "Source on Save" the function will be executed and you can use Ctrl + 2 to jump into command line and test the function directly.
Since I am working with R, my datasets are much bigger. But I am remembering starting coding in python and vi, I updated my setting in a way to execute the code on save, since these little scripts where done in less then 10 seconds...
So maybe it is just not standard to work with small datasets... But I can still recommend it, for development, to use only 10% of a normal dataset. It will speed up the graphics creation and a lot of other things as well. Test it with the complete dataset every now and then.

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

Is there a hack to be able to run the current line or selection in RStudio without moving the cursor?

UPDATE (April 2013): As per answer below, RStudio no longer jumps cursor on selection.
I'm running RStudio 0.97.168.
I like to use the script editor in RStudio like a console. Thus, I run a line of code and then edit it a little bit and re-run it. I often also explore objects by selecting some of the code and running the selection and then progressively altering the selection. At present RStudio always moves the cursor after running a line of code. The cursor can move to a variety of places. Typically the cursor moves to the next line of R code, but depending on the context, it could move to the end of the code block or the next line. It's really frustrating having to constantly move the cursor back to where I want it.
While I often appreciate the default cursor movement behaviour, I'd like to have the option to run the selection or the current line without the cursor moving.
I've raised this as a suggestion on RStudio support.
I'd like to be able to have a shortcut key like "Cmd+Alt+Enter" that runs the current line or selection and does not move the cursor in the script editor.
I realise that this is not currently supported, but I was wondering whether there might be some creative hack that could enable the cursor not to move after running a command or even a patch or perhaps some sort of external macro.
For anyone who ends up here in 2020:
Ctrl(or Cmd) + Enter: Will run current line and jump to the next one. If a code portion is selected, run the selected code without jumping further.
Alt + Enter: – Will run the current line of code without moving the cursor to the next line, useful if you want to run it multiple times.
(Source)
For this kind of flexibility, I suggest you use the editor Sublime Text 2, add in the package installer by Will Bond and then install the SublimeREPL package which will allow you to use an R interpreter within ST2 (or BASH prompt, Python / Ruby / whatever interpeter, concurrently if you wish).
You can then alternate between your code and the interpreter without lifting your fingers from the keyboard and your cursor will be at the same point every time when you want to switch back.
Sublime Text will also allow you to write a custom keybinding to automate this task.
I cannot recommend using Sublime Text 2 highly enough when coding for R. You can even pass files directly from ST2 into RStudio very easily if you like using the plot panes (very easy to do with the SidebarEnhancements package in ST2).
RStudio is awesome for many things -- especially now with Knitr, builds etc etc. But ST2 with an R REPL is many orders of magnitude more powerful for general code writing / editing than RStudio.
Sorry it's not RStudio specific, but it is a nice workaround!
I updated to version 0.98.83 of RStudio using the daily build section.
It appears that at some point in recent versions of RStudio, the cursor no longer jumps when code is run from a selection in the script window.
That's great news.

Can I move the cursor to revise in R?

I input something into the R console:
> ta <- function(x,y){
+ x=x+2
+ y=y+1
+
Now my cursor is on the fourth line, I found it's x=x+1, not x=x+2.
Can I move my cursor onto the second line to revise x=x+2 into x=x+1?
As far as I'm aware, you can't do what you describe. What you can do is press Esc to cancel entering into the console and start afresh writing it in.
Are you using an IDE? Or are you writing directly into the RGui? If the latter, I heartily recommend using RStudio. It will make your life a lot easier. You'll be able to to enter text into one window and then send it into the R console when you're ready.
Alternatively. R does have an editor (File > New script) which you can use to send lines, or you can even use a txt file off to the side and only send lines when you're ready.
AFAIK, there is no way to edit the function while R is still waiting for you to close the function call. So first, I think you need to finish writing your function by typing }. Once completed, you can then do one of a few things, all of which are outlined in good detail here. I won't bother regurgitating those perfectly good answers, but do recommend you check them out. Finally, if you aren't currently using an IDE to help develop your R code, that will make your life much easier. Which IDE will be best for you is also quite subjective, but has been covered on SO here before. FWIW, I've had good luck with RStudio which is platform independent and all that good jazz...your miles may vary.
If you are running R from a terminal, you can press ctrl + c to cancel your entry and start over.

Resources