How can I duplicate the terminal/prompt in a file like using history + sink - r

I know the sink command can divert the stdout to a file, but basically if I do this in the command window:
library(data.table)
a = 1;
b = 2;
a
[1] 1
Only the last line [1] 1will be printed in the file.
Is there a way my whole command window could be printed to a file like it is done with sink ?
NOTE: I want it to be done each time I write something to avoid losing everything if R crashes, meaning I do not want to have to type printAllCommandToFile() for this to be done

What about txtStart from the "TeachingDemos" package? See here.
Sometimes, when introducing students to R, I've recommended it to help them remember what they did and what the results were, a situation somewhat like you describe.
In my experience on a Linux machine, even if you close R without calling txtStop, the output is saved to whatever text file you had specified at the start of your session.

You do not say what environment you are in. On my machine (Mac) I can type cmd-A (for select-all) and cmd-S (for save to file) and get a save-dialog. Pretty sure something similar exists on Windows and *Nix devices as well.

Related

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])
}

Rgui command-line for sourcing R file

What command line option to use behind Rgui.exe for immediately sourcing an R source file? Instead of having to type source("c:\MyGreatSource.R") manually afterwards. Something like:
Rgui.exe --source "c:\MyGreatSource.R"
Sounds like a simple question answered in any beginner's manual, but I couldn't find such an option anywhere.
I found a workable solution, maybe others are interested. Again, what I like to do is to start the Rgui and work there. All my work environment and functions are defined in an R source file, which I constantly develop further during working. So each of my commands in the GUI starts with Load1(); where Load1 is a function which simply sources my R file, to update the changes I have just made. Obviously, Load1 is also defined in my R file, so I need to get it in the first place, without much effort. I have set the command-line options for neither loading nor saving the workplace; I don't like my old mess from the previous session with test variables and so.
However, my solution now is to just create a workplace RData file which only contains the definition of my Load1 function. This workplace file is easily loaded at every start by just adding its path into the command-line options "D:\MyLoad1.RData"
I use a AutoHotkey Script
run,C:\Program Files\R\R-3.3.3\bin\x64\Rgui.exe
WinWait,RGui (64-bit)
WinWaitActive,RGui (64-bit)
Sleep 100
Send,source("%1%")
Send,{enter}

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

Starting R and calling a script from a batch file

I have an R-based GUI that allows some non-technical users access to a stats model. As it stands, the users have to first load R and then type loadGui() at the command line.
While this isn't overly challenging, I don't like having to make non-technical people type anything at a command line. I had the idea of writing a .bat file (users are all running Windows, though multi-platform solutions also appreciated) that starts R GUI, then autoruns that command.
My first problem is opening RGui from the command line. While I can provide an explicit path, such as
"%ProgramW6432%\R\R-2.15.1\bin\i386\Rgui.exe"
it will need updating each time R is upgraded. It would be better to retrieve the location of RGui from the %path% environment variable, but I don't know an easy way to parse that.
The second, larger problem is how to call commands for R on startup from the command line. My first thought is that I could take a copy of ~/.Rprofile, append the extra command, and then replace the original copy of the file once R is loaded. This is awfully messy though, so I'd like an alternative.
Running R in batch mode isn't an option, firstly since I can't persuade GUIs to display themselves, and secondly because I would like the R console available, even if the users shouldn't need to use it.
If you want a toy GUI to test your ideas, try this:
loadGui <- function()
{
library(gWidgetstclck)
win <- gwindow("test")
rad <- gradio(letters[1:3], cont = win)
}
Problem 1: I simply do not ever install in the suggested default directory on Windows, but rather group R and a few related things in, say, c:/opt/ where I install R itself in, say,c:/opt/R-current so that the path c:/opt/R-current/bin will remain constant. On upgrade, I first renamed to R-previous and then install into a new R-current.
Problem 2: I think I solved that many moons ago with scripts. You can now use Rscript.exe to launch these, and there are tcltk examples for waiting for a prompt.
I have done similar a couple of times. In my cases the client was using windows so I just installed R on their computer and created a shortcut on their desktop to run R. Then I right click on the shortcut and choose properties to get the propertiest dialog. I then changed the "Start in" folder to the one where I wanted it to run from (which had the .Rdata file with the correct data and either a .First function in the .Rdata file or .Rprofile in the folder). There is also a "Run:" option that has a "Minimized" option to run the main R window minimized.
I had created the functions that I wanted to run (usually a specialized gui using tcltk) and any needed data and saved them in the .Rdata file and also either created .First or .Rprofile to run the comnand that showed the gui. The user double clicks on the icon on the desktop and up pops my GUI that they can work with while ignoring the other parts.
Take a look at the ProjectTemplate library. It does what you want to do. It loads used libraries from a batch file an run R files automatically after loading as well as a lot of other usefull stuff as well...
Using the answer from https://stackoverflow.com/a/27350487/41338 and a comment from Richie Cotton above I have arrived at the following solution to keeping a script alive until a window is closed by checking if the pointer to the window is valid.
For a RGtk2 window created and shown using:
library(RGtk2)
mainWindow <- gtkWindow("toplevel", show = TRUE)
Create a function which checks if the pointer to it exists:
isnull <- function(pointer){
a <- attributes(pointer)
attributes(pointer) <- NULL
out <- identical(pointer, new("externalptr"))
attributes(pointer) <- a
return(out)
}
and at the end of your script:
while(!isnull(mainWindow)) Sys.sleep(1)

Resources