Extract what was printed deep in the R console - r

When I execute commands in R, the output is printed in the console. After some threshold (I guess, some maximum number of lines), the R console no longer shows the first commands and their output. I cannot scroll up that far because it is simply no longer there.
How can I access this "early" output if it has disappeared from the console?
I care mostly about error messages and messages generated by my own script. I do use a script file and save my results to a file, if anyone wonders, but this still does not help solve my problem.
(I have tried saving the R workspace and R history and then loading it again, but did not know what to do next and was not able to find what I needed...)

Related

How to exit R in the middle of a command?

I am trying to run code in R and I have repeatedly run into the very frustrating issue that, unlike in Terminal when you can just press control-C on the keyboard, or Python when you can just enter exit(), in R it does not appear to be possible to exit a command you are currently typing to get back to the basic command line-type interface. That is, when I'm typing some code in R, I have a bunch of plus signs to the left of what I'm typing rather than > symbols, and, rather than execute what I have typed, I want to exit it and return to having > symbols and thus be able to type a whole new command while keeping the R window and workspace open, I find it impossible to do so. Instead I end up having to just close the entire R window, save the workspace, and reopen it which is way more steps than I'm sure are necessary. I already looked around online trying to find a way to exit R commands in the situation I described, and I found:
1. "stopifnot("something that is not true")", which worked the first time I tried it but not the second (why? no idea)
2. "stop("string")", which did nothing when I tried it
3. "quit()", which also did nothing

R: Sink(type="message") for error reporting - can I get a line number?

TL;DR: I'm using sink() to log errors during a script run, and saving them to a dataframe that can be viewed post-run, to highlight errors. I'd like a way to include the error line number, if possible.
'
Long version: I'm writing an R script to process national weather datasets, which sometimes contain anomalies - missing data, unexpected symbols, etc. It's possible that inconsistencies in the data could cause errors in the script, which is fine for me as the programmer - I can identify and fix them. However, my eventual goal is to make it broadly applicable to any national weather dataset - this means it might be used by people with little R knowledge. The script is presently ~700 lines long and will be getting quite a bit longer, with a number of user-defined functions. This makes reviewing the console history rather tedious, especially for novice R users.
My solution so far has been to save all error and warning messages generated during a script run to a table, which would be the first thing the user sees after a run, forcing them to acknowledge errors. I'm using the sink() function (I found the method on another SO post, attributed in the code comments below), and it works beautifully, EXCEPT that I can't figure out a way to log the line number for error messages. Traceback() won't work in this context, as I want all errors, not just the most recent one in the stack.
As written, my code is below. I mainly work in RStudio, so I run this by pasting the block into the console.
# Method accesed online Nov 24, 2016, at:
# http://stackoverflow.com/questions/11666086/output-error-warning-log-txt-file-when-running-r-script-under-command-line
setwd(tempdir()) # tempdir() creates names for temporary files
# Capture messages and errors to a file
zz=file("all.Rout",open="wt") # file() creates a file connection and opens it
# in wt="write text mode".
sink(zz,type="message") # sink diverts R output to a connection - in this case, the error log, zz
# test out some error samples (4)
try(log("a")) # try runs an expression and allows user code to handle error-recovery
z x a # try() is not necessary - any error will be flagged and entered to the log
mean()
sds(42)
# Display log file
readLines("all.Rout")
error.log=data.frame(readLines("all.Rout")) # write these to an error log DF
# Reset sink, close connection
sink(type="message") # this prevents diversion of messages -
# they will now appear in console, as default
close(zz) # close the error log connection
remove(zz) # blank from mem
# OK, this is good - but can I get line numbers to output to the DF?
Can anyone recommend a way to make this work with sink()?
Alternatively, if you know of some other way to get to my desired output (a list/table of error/warning messages and their locations in the code), I'm all ears.

Why is source speed different from RStudio console line code?

I have a script with self-written functions (no plots). When I copy-paste that script into the R-Studio console, it takes ages to execute, but when I use source("Helperfunctions.R") it doesn't take more than a second.
Question: Where does the difference in speed come from?
I am aware of two differences between running code via the source() function vs. entering code at the R-Studio console:
From ?source:
Since expressions are not executed at the top level, auto-printing is not done.
The way I understand this: source() will not plot graphs (unless made specific with e.g. print(plot)), while the R Studio console codes will always plot graphs. I'm sure this will affect the speed of execution to a certain degree, but this seems irrelevant in my case, because there are barely any plot calls.
And:
(...) the complete file is parsed before any of it is run
I have been working with R for a while now, but I'm not sure whether this relevant for the speed-issue I'm having. Is it possible that completely parsing all code "before any of it is run" speeds up the execution of my helper functions script by a factor of a hundred?
Edit: I'm using R version 3.2.3.
The issue is not source() vs. console line code. Instead, it is an issue of how RStudio sends code from the source pane to the console.
When I copy the content of Helperfunctions.R and run it in RGui (instead of RStudio), the code is executed with nearly the same speed as when I use source("Helperfunctions.R") in RStudio.
Apparently, lines of code always (?) require more execution time in RStudio than in RGui. Even though you may usually not notice the time-difference when executing a couple of lines in the console, it seems to make a huge difference when, say, 3.000 lines of code are being executed in the R Studio console at once.
My understanding is that upon using source("Helperfunctions.R") in the RStudio source pane, the code is not actually sent to the RStudio console (which would have been slow), but is actually executed directly in the R language.

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

Slow or stacking file.choose() in R

If I have more data loaded in R I'm having difficulties with opening and choosing new file via file.choose() and later upload via read.csv(), but I would not get to that point since the file.choose function stacks and the R "crushes" and reports something like "unidentified error occurred and that the R must restart".
I'm using RStudio and running this on Windows 7. The hardware is up to date.
Could someone point me on why this is happing and what would be a remedy against this. Are there other options to select file? I know I can insert the path right into the read.csv command, but the (file is different every time).
EDIT:
The error just happened again. I can not reproduce the error so it happens rather only with high likelihood if the conditions for it are met.
The error reads as: R Session Aborted.R encountered fatal error. The session was terminated. And in window: "Start New Session".
EDIT 2:
I would just rephrase my question. The question is whether there is other option like command or package that deals with choosing a file. [file.choose()]
The error can not be reproduced and hence I can not expect someone gives reasonable comment on this. But if this occurred someone in the past and solved it, I would like to hear about it. Thanks.
EDIT 3: Further to the error. I have spotted just now sentence in red in Console: Error: Unable to provide connection with R

Resources