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

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.

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.

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.

Run R (on Linux) interactively with a simple repl (no readline, no assumed terminal)

I'd like to run R as an inferior process. I'd like R to display help pages as html (in the browser) and to display plots as if it were run interactively. I know I can run R with the --interactive argument but then R seems to assume it's running on a terminal end emit control sequences.
How should I run R to get html help pages & plot (as with --interactive) and simple textual output with no control sequences?
If I use R, it assumes to be run non-interactively (html help pages or plots won't work but the output contains no control sequences).
If I use R --interactive --no-readline, it runs interactively (help pages and plots work as expected) but the output is garbled and difficult to parse since it assumes to be running on a terminal.
Is there a way to control the assumptions R makes about the terminal it's running in?
It seems that argument order matters. (Part of) the problem gets resolved when calling R as R --no-readline --interactive.

R function called when pressing Ctrl+D

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.

R unix terminal pager

I'm using R on OS X 10.6 and I prefer the unix console to the R.app for my work. If I issue a help command eg ?print the help content opens through a pager (i tried most and less), which however then hides out the content if I exit it bringing me back to the R input line.
What I really want is that the pager output stays on the screen even after I exit it back to R (hitting q).
I get this desired behaviour on other Readline-based Cli like psql for example, but not on R. Any hints on how this gets configured would be greatly appreciated.
The console pager that R uses can be set with the options function. With less, the -X option suppresses the terminal clearing at exit. So, if the less binary is located in "/bin" (not sure where it's located in OS X), this should work:
> options(pager="/bin/less -X")
If you want this to be the default behavior every time you start R, you can place the above command in your ~/.Rprofile file, which is run automatically at startup.
Alternatively, you can set a export LESS=-XF in ~/.bashrc and this will have an effect across all programs that use less as a pager. The F option would further exit straight away if the content is less than a page, which I find quite useful.

Resources