Search code examples
rshellsessionbatch-fileinteractive-mode

use a batch script to run an R script interactively in the R shell


I can run an R script non-interactively from a batch file and save the output.

I can open an interactive R session using a batch file.

I can open R AND run a script from a batch file by doing one, then the other (but then the variables from the script are not available in the interactive session).

What I have not been able to do is to use a batch file to open an interactive R session and run a script from within that interactive session. How can I do this?

Regarding workarounds:

The purpose is to use the script to load and process a very large dataset daily, and then have that available for use during an interactive session in R, so using a non-interactive session is not an option for this task. Likewise I am aware that I can run an interactive session using the Windows command prompt but for a variety of reasons I do not want to do that. I want everything loaded into the R shell for use there. I realize Task Scheduler would be useful for this, but unfortunately, I do not have permissions to modify Task Scheduler. I am only allowed to use a batch file which is scheduled then by IT.

I apologize if I simply lack the vocabulary to search for the answer to my question effectively and welcome answers directing me to previous questions.

Thank you.


Solution

  • One possibility would be to create a Rprofile.site script that sources the setup file that loads the data. Then, from your batch script set the R_PROFILE variable for this session to point to this Rprofile.site script.

    In your batch script,

    @echo off
    set R_PROFILE=C:\path\to\Rprofile.site
    Rterm.exe
    

    In Rprofile.site

    .First <- function() {
        print("Loading some stuff")
        source("setup.R")
    }
    

    In setup.R

    dat <- data.frame(x=1:10)
    

    I guess you could do with the setup.R file and put it all in the .First function as well.