3

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:

enter image description here

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?

Louis15
  • 295
  • 3
  • 12
  • What is the purpose ? Why not open a session and call the script instead? – cderv Aug 26 '17 at 11:41
  • @cderv because I am automatizing calls to R scripts via other software. – Louis15 Aug 26 '17 at 11:43
  • you should not need to have the R session still open after the rscript call though. I am not sure to understand why you want that. Your current solution is of to call R scripts from other software – cderv Aug 26 '17 at 11:45
  • @cderv I am implementing a simple R IDE within my application. Also, this is required for many more usages, like for instance to have a R console inside Sublime, etc. – Louis15 Aug 26 '17 at 11:54

1 Answers1

3

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.

G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
  • Thanks for your answer. The problem with that solution, though, is that it will require such modifications for every file. I should have specified that I needed it to work without doing that. I will update the question with more details about my usage case. – Louis15 Aug 26 '17 at 21:21
  • Not so. Just set the environment variable and then start R or write a simple batch file to do it. e.g. `(set STARTUP_FILE=C:\test.R) && R` or if your batch file is called myR.bat then run `myR C:\test.R` – G. Grothendieck Aug 26 '17 at 23:36