I'm trying to call a simple python script from within R using system2(). I've read some information I found vague that said if 'too much' memory is used, it won't work.
If I load a large dataset and use some information in it to use as arguments to pass into system2(), it will only work if I manually click "Restart R" in call Rstudio.
What I want:
df <- read.csv('some_large_file.csv')
###extracting some info called 'args_vec'
for(arg in args_vec){
system2('python', args)
}
This won't work as is. The for loop is simply passed over.
What I need:
df <- read.csv('some_large_file.csv')
###extracting some info called 'args_vec'
###something that 'restarts' R
for(arg in args_vec){
system2('python', args)
}
This answer doesn't quite get what I want. Namely, it doesn't work for me within Rstudio and it calls "system" (which presents the same problem as "system2" in this case). In fact, when I put the answer referenced above in my Rprofile.site file, it just immediately closed rstudio:
I tried the suggestion as a normal function (rather than using "makeActiveBinding", and it didn't quite work.
##restart R in r session -- doesn't work
makeActiveBinding("refresh", function() { system("R --save"); q("no") }, .GlobalEnv)
##nor did this:
refresh <- function() { system("R --save"); q("no") }
I tried a number of variations of these two options above, but this is getting long for what feels like a simple question. There's a lot I don't yet understand about the startup process and "makeActiveBinding" is a bit mysterious. Can anyone point me in the right direction?
In Rstudio, you can restart the R session by:
command/ctrl + shift + F10
You can also use:
.rs.restartR()
RStudio has this undocumented rs.restartR() which is supposed to do just that: restarting R.
However, it does not unload the packages that were loaded, nor does it clean the environment, so that I have some doubts about if it restarts R at all.
If you use RStudio, use the menu item Session > Restart R or the associated keyboard shortcut Ctrl+Shift+F10 (Windows and Linux) or Command+Shift+F10 (Mac OS). Additional keyboard shortcuts make it easy to restart development where you left off, i.e. to say “re-run all the code up to HERE”:
In an R script, use Ctrl+Alt+B (Windows and Linux) or Command+Option+B (Mac OS)
In R markdown, use Ctrl+Alt+P (Windows and Linux) or Command+Option+P (Mac OS)
If you run R from the shell, use Ctrl+D or q() to quit, then restart R.
Have you tried embedding the function call within the apply function, rather than a for loop?
I've had some pieces of code that ran the system out of memory in a for loop run perfectly with apply. It might help?
For those not limited to a command that want something that actually resets the system (no prior state, no loaded packages, no variables, etc.) you can select Terminate R from the Session menu.
It is a bit awkward (asks you if you are sure). If anyone knows something like clear all or really clear classes in MATLAB let me know!
Related
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}
Question regarding RStudio. Suppose I am running a code in the console:
> code1()
assume that code1() prints nothing on the console, but code1() above takes an hour to complete. I want to work on something else while I wait for code1(). is it possible? Is there a function like runInBackground which I can use as follows
> runInBackground(code1())
> code2()
The alternatives are running two RStudios or writing a batch file that uses Rscript to run code1(), but I wanted to know if there is something easier that I can do without leaving the RStudio console. I tried to browse through R's help documentation but didn't come up with anything (or may be I didn't use the proper keywords).
The future package (I'm the author) provides this:
library("future")
plan(multisession)
future(code1())
code2()
FYI, if you use
plan(cluster, workers = c("n1", "n3", "remote.server.org"))
then the future expression is resolved on one of those machines. Using
plan(future.BatchJobs::batchjobs_slurm)
will cause it to be resolved via a Slurm job scheduler queue.
This question is closely related to Run asynchronous function in R
You can always do this, which is not ideal but works for most purposes:
shell(cmd = 'Rscript.exe some_script.R', wait=FALSE)
RStudio as of version 1.2 provides this feature. To run a script in the background select "Start Job" in the "Jobs" panel. You also have the option of copying the background job result into the working environment.
The mcparallel() function in the parallel package will do the trick, if you are on Linux, that is ...
library(parallel)
Job1 = mcparallel(code1())
JobResult1 = mccollect(Job1)
My emacs/ess session crashes when I try to access help. This happens if I have two packages loaded with the same functions; for example:
library(lubridate)
library(data.table)
?month
In Rgui interface pops out and asks to choose from which packages I want help. Emacs just crashes. Similar issues happens with install.packages, but there is a way to specify mirror Is there a way to install R packages using emacs?
Is there a similar trick with help?
Well, there is no full proof solution for time being as nobody really understands why these crashes happen. I assume you are on windows, right?
There are plans in ESS to completely internalize all the help (and other) calls in order not to depend on R dialogs. Hopefully in the next version.
For time being put this into your .Rprofile
tis <- utils:::index.search
formals(tis)[["firstOnly"]] <- TRUE
assignInNamespace("index.search", tis, "utils")
It basically makes help system to pick the first package with the found topic. In your case month help page in data.table package will be ignored. Not a big deal as common topic names are quite rare anyways.
I found out that starting library(tcltk) solves this problem. Menu appears even after it is called from emacs+ess. I added library(tcltk) to my Rprofile.site and now everything works great, install.packages() and accessing help when multiple packages load same function
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)
Is there a way I can make an alias, within R, that will execute q() and then restart a clean R session?
And yes, I am too lazy to type q() and then the letter R :)
If you're in RStudio:
command/ctrl + shift + F10
You can also use
.rs.restartR()
Depending on how you start R try placing one of these lines into your .Rprofile file:
makeActiveBinding("refresh", function() { shell("Rgui"); q("no") }, .GlobalEnv)
makeActiveBinding("refresh", function() { system("R"); q("no") }, .GlobalEnv)
Then entering this into the R console:
refresh
will shut down the current session and start up a new one.
I found that .rs.restartR() works similar to pressing ctrl+shift+F10. but dose not unload the packages
As another alternative, Emacs ESS (>= 16.10) can reload the inferior R process via inferior-ess-r-reload-hook which is bound to C-c C-e C-r by default.
After looking for a solution to this, I solved my problem based on this solution here, using the R Package RDCOMClient.
The solution bellow just work within RStudio (Windows), once it simulates the keypresses ctrl+ shift + F10.
The RDCOMClient package must be installed with the command bellow:
install.packages("RDCOMClient", repos = "http://www.omegahat.net/R")
The code to simulate the keypresses within RStudio (Windows 10) are:
library(RDCOMClient)
wsh <- COMCreate("Wscript.Shell")
wsh$SendKeys("^+{F10}")
In the last line in the code above, the 'ctrl' key is represented by '^' and the shift key by '+'. All the explanations for this key representaions are available here.
Just after running the last line of the code above, the whole R session in RStudio will be reset, according to #steadyfish's comment. That is, it removes all the data from current session and unload all the loaded packages in the session.
Old post, but none of the answers quite work (for me, I'm using Windows, haven't tested others), so I'll add my solution. Some of my terminology might be off here, but this should get the point across:
Above answers don't quite work
Most of the answers submitted here involve using shell or system which doesn't quite work because while they open a new R console and do instruct the original console to close, the new console is a process running in the application context of the old console. That means the original console cannot close until the new console closes. Some of the users above such as hedgedandlevered reported that closing the original console forces the new console to close. When I try, the new console does open, but the old console remains open in a frozen state until the new console is closed.
The basic problem is calling shell or system does not change the application context from the original console to the new one, and therefore the original process cannot terminate until the new console closes.
Alternative that works for me
Instead use shell.exec which would normally be used to open a file in the default application based on file type. When used on a .exe, apparently, it runs the executable. The important difference, though, is that the system starts the application in it's own separate context. So here's the code that works for me:
makeActiveBinding("restart.R", function() { shell.exec(paste0(R.home(),"/bin/x64/Rgui.exe")); q("no") }, .GlobalEnv)
You'll need to edit the file path /bin/x64/Rgui.exe to match whatever you use to start R. You just put this line in your .Rprofile file, then you can call it by entering restart.R in your R code.
The downside of this over other methods is that you can't pass command line arguments like --no-save as you would with just shell, but at least this will let you close out the original R process.
Write this function in your .Rprofile
r <- function() {
assign('.Last', function() {system('R')}, envir = globalenv())
quit(save = 'no')
}
r() restarts you R session. Loaded packages will not reload. Your environment wont be saved.
Works for Linux. No idea of what may happen on other OS
In line with Martin Morgan's idea of using .Last(); this restarts R with the same set of command-line options as previously called:
restart_r <- function(status = 0, debug = TRUE) {
if (debug) message("restart_r(): Customizing .Last() to relaunch R ...")
assign(".Last", function() {
args <- commandArgs()
system2(args[1], args = args[-1])
}, envir = globalenv())
if (debug) message("restart_r(): Quitting current R session and starting a new one ...")
quit(save = "no", status = status, runLast = TRUE)
}
I needed the same refresh session functionality on windows and I ended up with a slightly modified version of the code:
makeActiveBinding("refresh", function() { shell(paste0("start \"\" \"", R.home(), "/bin/x64/Rgui.exe\"")); q("no") }, .GlobalEnv)
On windows you need to modify the Rprofile.site file. It is under R's etc directory. Also watch out for the last part of the path the bin/x64 can change according to your system configuration. I hope this will help others too.
I think, one realizes the best use of R by setting a current working directory in options. Then whenever your workspace /session file starts showing you up or has enough of your work in it (in between projects) you can just rename this default session file in the working directory after closing R and R/Rstudio will automatically start you in a new workspace/session file, without disturbing your current work.
Remember to quit R and rename the current session file
Of course if you do not want to save the current work you have to make sure you reset objects or operations on them were done after copying from original objects so they are as is. Trust me, knowing you can always load the old workspaces is a temptation but is more useful than not.
In short quit R, it gives you some gap while quitting means this workspace is full, rename it after completing the quit and restart R/Rstudio with a fresh workspace. You can always load select objects in the new workspace. Ideally all important work should be in Project directories but you still need a history of your jobs to go back to at times and saved sessions come in useful at some point once you are on longer projects. If you don't need any of it just rm(list=ls())
Also, I like the RDComClient idea by #Eduardo Alvin but it has been discontinued.
ALTERNATIVE OPTION
A simple alternative to get rid of the baggage at any time inside your workspace is to use save.image
save.image("Rstreamingscience.data")
quit(save='no')
load("Rstreamingscience.data") ##G:/ADA registers##
save.image("Rstreamingscience.data")
This leaves you free to come and go as you please and open as many workspaces as you need.
makeActiveBinding("refresh", function() { system(paste0(R.home(),"/bin/i386/R")); q("no") }, .GlobalEnv)
or with --save or --no-save
paste0(R.home(),"/bin/i386/R --no-save")
I think this is what you need if you've used setwd() before calling refresh (although neither this nor the original version works for me, since it restarts R then closes itself, a new window is never opened. If anyone can comment on this, please do so)
I have written the following function.
Remember! You can only use it once, then you have to reload it after the R session restarts.
clc <- function() {
rm(list = ls(envir = globalenv()),envir = globalenv()) #clear Vars from global enviroment
gc() #grabage colector
cat("\014") #clc
.rs.restartR() #clear session
}
Sometimes detaching a package also helps.