R function called when pressing Ctrl+D - r

What function (if any) is called when pressing Ctrl+D to exit R repl? I saw in a few questions, such as:
How to disable "Save workspace image?" prompt in R?
Expert R users, what's in your .Rprofile?
code that led me to believe it's calling either function q or quit.
The reason I want to override is to make the pesky:
Save workspace image? [y/n/c]:
prompt on exit go away. However, overriding the function in .Rprofile such as:
quit <- function(...) {
print(1)
}
and similarly for q did not work - i.e. pressing Ctrl-D did not actually print number 1, went straight to the prompt.
The solutions presented in the above links did not seem to work. R version used:
R version 2.15.2 (2012-10-26) -- "Trick or Treat"
Copyright (C) 2012 The R Foundation for Statistical Computing
ISBN 3-900051-07-0
Platform: x86_64-pc-linux-gnu (64-bit)

Ctrl-D does not call any function, it is special keyboard interrupt.
Try pressing Ctrl-D, then answer c for cancel. If you press the up arrow to get the last command, you'll see it's not there.
To override the pesky Save workspace image? [y/n/c]:, see the answer to this question:
To summarise you have three options:
Calling R --no-save instead of R,
Loading the following in the interactive R session (won't work from .Rprofile):
require(Defaults)
setDefaults(q, save="no")
useDefaults(q)
Or put the following in your .Rprofile:
# Set hook to be run when Defaults is attached
setHook(packageEvent("Defaults", "attach"),
function(...) { setDefaults(q, save="no"); useDefaults(q) })
# add Defaults to the default packages loaded on startup
old <- getOption("defaultPackages");
options(defaultPackages = c(old, "Defaults"))
EDIT:
Here's another hack I can think of since the above haven't worked for your case. It's not an R solution, but might do the trick?
First, move you R executable file (for the purposes of this example i'm going to assume it's in /usr/bin/) to a new file, something like:
sudo mv /usr/bin/R /usr/bin/Rold
Now set up a new bash script as /usr/bin/R:
#!/bin/bash
/usr/bin/Rold --no-save "$#"
and chmod it to have the right permissions.

Related

How to run Python, R, Octave or Julia using BowPad?

I try using a very light-weighted editor BowPad to edit and run codes.
Take running R as an example, which has been added to Windows PATH Environment Variable D:\R\R-3.6.2\bin\x64
I try to take some following steps:
I built a test.r writing some testing line codes as 1+2; plot(1:10)
Menu --> Run --> Configure custom commands
Command Name: run R
Command Line: D:\R\R-3.6.2\bin\R.exe $(SEL_TEXT)
$(LINE) The line where the cursor is
$(POS) the position where the cursor is
$(TAB_PATH) the path to the file of the active tab
$(TAB_NAME) the file name without extension of the current tab
$(TAB_EXT) the file extension of the current tab
$(TAB_DIR) the directory of the file of the active tab
$(SEL_TEXT) the selected text or the word at the cursor position
$(SEL_TEXT_ESCAPED) like $(SEL_TEXT) but escaped, useful for urls
When I press to choose run R to run the code, something wrong happens!
It will open a Rterm(64-bit) window each time when I run R!
it shows RGUMENT '1+2' __ignored__ or ARGUMENT 'plot(1:10)' __ignored__
Did I missing something ? BTW, can we set some shortcuts keys for running Python, R, Octave or Julia?
Also, when I reach the homepage of BowPad for more information, little usage of this software can be found!
R.exe refers to Rterm. You can use Rgui.exe instead but that won't automatically process arguments. I think what you likely want is to send the selected text to a running R session rather than starting up a new R session each time.
To do that
download this file and optionally place it on your path https://raw.githubusercontent.com/ggrothendieck/batchfiles/master/clip2r.js
in the Bowpad Run | Configure window configure a Run R command as the following (or if clip2r.js is not on your path use the entire pathname). It should be just like this with no arguments.
clip2r.js
From the Windows cmd line if Rgui is running we see that tasklist | findstr Rgui finds Rgui as the R gui process and you can create additional js scripts by editing clip2r.js replacing Rgui in the js script with whatever is the appropriate word to locate python, julia, octave or other R front end assuming again that they are running.
Now to invoke it from within Bowpad:
ensure that your Rgui session is already running and
from within Bowpad select the code you want to run and copy it to the clipboard and then invoke Run R. For example, to run everything use ctrl A ctrl C ctrl R 0 assuming that Run R is in position 0 in the configure menu. Alternately use the mouse with the Ribbon.
Regarding the comment about difficulty finding help, it looks like Bowpad is based on Scintilla so the documentation for it and the related SciTE editor likely apply to Bowpad too. You can also check the Bowpad source code on github.

How to call littler without sourcing ~/.Rprofile?

It seems that when I call littler from the command line, it will source ~/.Rprofile. Is there a way to prevent it from sourcing ~/.Rprofile?
It goes both ways---that we are now reading ~/.Rprofile is in large part due to users who wanted this feature, as opposed to you not wanting it :)
But there is a (simple and easy) fix: use interactive(). Witness:
edd#rob:~$ r -e 'print(interactive())'
[1] FALSE
edd#rob:~$ r -i -e 'print(interactive())'
Please do not apply R like a magic answers box, because you can mislead
others and cause harm.
-- Jeff Newmiller (about how much statistical knowledge is needed
for using R)
R-help (May 2016)
[1] TRUE
edd#rob:~$
So what happened here? First, we tested interactive(). It came back FALSE. This is the default. Nothing happened.
Second, I added the -i switch to enfore interactive mode. It printed TRUE, but more. Why?
Well my ~/.Rprofile in essence looks like this
## header with a few constant settings, mostly to options()
## TZ setting and related
local({ # start of large block, see Rprofile.site
if (interactive()) {
if (requireNamespace("fortunes", quietly=TRUE)) {
print(fortunes::fortune())
#more stuff
}
})
and that governs my interactive R sessions on the console, in Emacs/ESS, in RStudio, and my non-interactive r calls from, say, crontab.
So in short: yes, it is always read. But yes, you can also skip parts you do not want executed.

Rscript - Using same R-file, The R terminal behaves different compared to Rstudio

Problem: Using same R-file, The R terminal behaves different compared to Rstudio.
When running below R-file several times, in Rstudio I get the correct behaviour.
First run [count=20], rest of run [count=1].
When running same R-file several times from a terminal, using [Rscript]:
First run [count=20], rest of run [count=20].
Wanted behaviour:
I need the R terminal to behave same as R studio , creating counter with value [20] and for the rest of the times put it to value [1].
My environment:
Ubuntu Linux 18.04
R-studio: 1.1.453
Terminal (Bash 4.4.19, R v.3.4.4)
Content of R-file:
setwd ("/tmp-r") # Set working directory.
# Set [count] to 20 if [count] does not exists.
# Set [count] to 1 if [count] exists.
if (!exists('count')) {
count <- 20
} else {
count <- 1
}
save.image() # Save.
With input from comments, I found 2 issues that solves the problem. Both for the minified test-script I published as a question, and my expanded script.
1) Add [load ('RData')], in the beginning since the load behaviour differs between Rstudio and R terminal. Rstudio dynamically update the global environment whenever you send in a change in the Rstudio console. R terminal loses the session between calls and therefor R terminal needs the R-file to start with [load ('RData')].
2) To solve my expanded script, I found out that the local [.Rprofile] has a [save.image('.RData)] at the end of the script. When removing that command in [.Rprofile] it solves the bigger script.

Running R via terminal in Windows and leaving R session open

Suppose that I have a R script called test.R, stored at C:\, with the following content:
x <- "Hello Stackoverflowers"
print(x)
To run it via terminal one could simply call:
Rscript C:\test.R
And as expected, the result will be:
However, what I wonder is whether there is a way to run test.R via Windows console but after that staying within the executed R session instead of closing and going back to the console cursor? That is, staying inside the R session instead of going back, in the image above, to C:\R\R-3.4.1\bin>.
For instance, when compiling Python code with python.exe I can easily accomplish a similar thing by passing the -i parameter to the python.execall.
How could I do that with R?
Add this to your .Rprofile:
STARTUP_FILE <- Sys.getenv("STARTUP_FILE")
if (file.exsts(STARTUP_FILE)) source(STARTUP_FILE)
and then set the indicated environment variable outside of R and then run R. e.g. from the Windows cmd line:
set STARTUP_FILE=C:\test.R
R
... R session ...
q()
Variations
There are many variations of this. For example, we could make a copy of the .Rprofile file in a specific directory such as ~/test, say, and add this code to that copy
source("~/test/test.R")
in which case R would only run test.R if R were started in that directory.

Restart R within Rstudio

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!

Resources