Is there a way to simulate Alt + Tab in R?
I've been looking for functions like SendInput, keybd_event, SendMessage and SendKeys.Send but couldn't find anything similar for R.
Some context:
I am using Rscript to plot and image that appears on the graphics device windows, then I call a function similar to readLines() and R waits for my input. The problem is that after the image pops up I have to go back to the terminal in order to give input and this makes my script less efficient.
I am using Ubuntu - Unity.
EDIT:
Is it possible to call bash from R? Maybe there is a function in bash that will make this possible?
If you are on windows, the following will work:
cls <- function () {
require(RDCOMClient)
wsh <- COMCreate("Wscript.Shell")
wsh$SendKeys("%{TAB}")
invisible(wsh)
}
cls()
Taken from here: http://r.789695.n4.nabble.com/clear-screen-td884932.html
More key presses can be found here: https://msdn.microsoft.com/en-us/library/8c6yea83(v=vs.84).aspx
Related
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.
I am creating a package in R that will have a GUI interface through the tcltk package. A front end function will get the data from the user through a GUI and call a back end function which returns the results back to the front end. I currently have written all of the documentation for the functions, and except for this part and a bit of bug testing the functions are also complete.
To help the user out, I want to be able to print the documentation. In Rstudio this displays it in the help window (it is important to note that this window is not created by my code through the tcltk package, this window is a part of Rstudio).
If my function only interacts with the user through the command line, I can get the help screen in Rstudio to update immediately. However, if I am using the graphics, the help window won't update until after the function is done, which defeats the purpose of having it print the help screen in the first place.
Below is an example of a GUI window created through the tcltk package. I'm using var.test as an example documentation here, so make sure your help window is on something else to see when the help screen updates.
require(tcltk)
print(help(var.test))
hi <- tktoplevel() #creates a window
ok <- function() # this function is called by pushing the button defined below
{
print("Goodbye, World!")
tkdestroy(hi) # destroys the window
}
print("Hello, World!")
ok.button <- ttkbutton(hi, text = "This is a button", command = ok) #defines the button
tkgrid(ok.button) #puts the button on the window "hi"
tkfocus(hi)
tkwait.window(hi)
As you can see, even calling the help function first, before the tcltk graphics window is even created, doesn't make the help window update. The print function still seems to work, as "Hello, World" is printed before one presses the button.
For my functions to work properly, I must use the tkwait.window(), otherwise the front end won't sync with the back end.
If getting the Rstudio window to update isn't really possible, then an alternative solution that uses a different window or program would be acceptable.
Add a small delay into your code after trying to print the help:
....
print(help(var.test))
# Sys.sleep(0.01) # too short
Sys.sleep(0.5) # long enough
...
This works in Linux and Windows...
I guess RStudio is not updating the GUI while executing the R command batch (all commands that you send to R at once) because it blocks updates executes R in a "blocking sub thread" and therefore behaving like "single threading" so that the GUI cannot be updated until the execution of the R batch ends.
The sleep function seems to return the control to the RStudio (GUI?) process so that it can update the GUI.
If you reduce the sleeping time too much you can observe partial updates of the RStudio GUI.
PS: Using process.events() does not work!
I've written quite a large R script (1000+ lines). Currently there is a rm(list=ls()) statement at the top of the script, as I need to test how it runs cleanly.
I run the code by ctrl + A, ctrl + R
The problem is is that this seems to take a long time in the Rgui to write each line to the console before running it. I feel R should be able to write to the the console faster than this and was wondering if there is a faster way to run a script.
(ie hide the lines written to the console and just run the script)
Best way is to simply source the document. If you have it saved then just type source("FullPathOfmyfile.R") and it will run without printing the commands, it will only print the output and print statements. Alternatively you can set echo = FALSE.
I am familar with matlab, but relatively new to r. I have an r script which produces many different graphical plot windows and takes some time in between each one. While this is running, I tend to be working on other things. The problem is every time a new graphics window is produced, it steals the focus, redirecting keyboard input away from what i am doing. Is there a way in r to prevent focus stealing when a graphical plot is produced?
I have searched everywhere but failed to find any reference to this. I am working in linux.
Any help greatly appreciated.
Thanks
Only on Windows: try putting a bringToTop(-1) in your function:
z <- function() {
plot(1:3)
bringToTop(-1)
}
z()
It will temporarily steal focus but then return it.
Another strategy on Windows:
z <- function(){
windows(restoreConsole=TRUE)
plot(1)
}
z()
I'm still thinking here...
If you are more interested in doing something else while the plots are being produced then I would suggest opening a pdf device so that all the plots go to a pdf file in the background and do not interfere with whatever else you are doing. Then when you are ready to look through the plots you just open the pdf file and look at the plots (and you can easily go back to previous plots this way).
If wmctrl is installed on your system, you can avoid losing focus by redefining the plot function like this:
plot <- function(...) {
graphics::plot(...)
system("wmctrl -a :ACTIVE:")
}
It seems to work quite well, in the fluxbox window manager at least. I tried different scenarios like switching to a different window during a long calculation before plot is called, and opening multiple plots.
Put it into your .Rprofile if you want it to persist.
I've an R script, that takes commandline arguments, where the top line is:
#!/usr/bin/Rscript --slave
I wanted to interrupt execution in a function (so I can interactively use the data variables that have been loaded by that point to work out the next bit of code I need to write). I added this inside the function in question:
browser()
but it gets ignored. A bit of searching suggests it might be because the program is running in non-interactive mode. But even more searching has not tracked down how I switch the script out non-interactive mode so that browser() will work. Something like a browser_yes_I_really_mean_it() function.
P.S. I want to avoid altering the rest of the script if at all possible. My current approach is to copy and paste the code chunks, needed to prepare the data, into an interactive session; but as the script gets more and more complex this is getting more and more unreasonable.
UPDATE: for anyone else with the same question, it appears the answer to the actual question is that it is impossible. Once you start R in a non-interactive mode the die is cast. The given answers are therefore workarounds: either you hack your code (remembering to unhack it afterwards), or you refactor to make debugging easier. (This comment is not intended as a criticism of the answers; the suggested refactoring makes the code cleaner anyway.)
Can you just fire up R and source the file instead?
R
source("script.R")
Following mdsumner's answer, I edited my script like this:
if(!exists("argv")){
argv=commandArgs(TRUE)
if(length(argv)!=4)usage_and_exit()
}else{
if(length(argv)!=4){
stop("Must set argv as a 4 element vector. E.g. argv=c(...)")
}
}
Then no other change was needed, and I was able to do:
R
> argv=c('a','b','c','d')
> source("script.R")
In addition to the previous answer, I'd create a toplevel function (e.g. doStuff) which performs the analysis you want to perform in batch. The function takes the cmd line options as input. In the batch script you source the script that contains this function and call it. In this way you can easily run the function in interactive mode and use e.g. browser().
In some cases, the suggested solution (workaround) may not work - for example, when the R code needs to be run as a part of an existing bash script. For those cases, I suggest to write in your R script into the bash script using here document:
#!/bin/bash
R --interactive << EOT
# R code starts here
argv=c('a','b','c','d')
print(interactive())
# Rest of script contents
quit("no")
# R code ends here
EOT
This way, print(interactive()) above will yield TRUE.
Sidenote: Make sure to avoid the $ character in your R code, as this would not be processed correctly - for example, retrieve a column from a data.frame() by using df[["X1"]] instead of df$X1.