Run R Interactively from Rscript

Run R interactively from Rscript

If I understand your question correctly, I was able to achieve this with littler, which I use in lieu of Rscript for scripting tasks that revolve around R. I'm running CentOS 7, and based on the code in your question it looks like you are on a Unix-like machine, so installing littler should not be an issue. For minimal reproducibility, I used the default shiny application and shiny-based Rmarkdown templates provided by RStudio, saving them as testapp (the project / application directory name) and testRMD.rmd, respectively. Then, I have the following scripts:


testapp.r

#!/usr/bin/env r

shiny::runApp(
"~/tmp/delete/testapp",
port = 7088,
launch.browser = TRUE,
host = "127.0.0.1")

testRMD.r

#!/usr/bin/env r

rmarkdown::run(
file = "testRMD.rmd",
dir = "~/tmp/delete",
shiny_args = list(
port = 7088,
launch.browser = TRUE,
host = "127.0.0.1"))

Set the permissions for these files so they can be executed -

[nathan@nrussell R]$ chmod +x testapp.r testRMD.r

(chmod +u ... should suffice, but regardless...), and you should be all set to run them from your terminal, etc...


[nathan@nrussell R]$ ./testapp.r
Loading required package: shiny

Listening on http://127.0.0.1:7088

Sample Image

[nathan@nrussell R]$ ./testRMD.r
Loading required package: shiny

Listening on http://127.0.0.1:7088

Sample Image


There is some additional command line output for the Rmd file that I omitted, but I'm sure this could be suppressed easily if desired. Anyhow, this seems to be working properly - both the shiny application and Rmarkdown application are interactive, just as when launched from RStudio - but if you had something else in mind please clarify.

Run Rscript interactive (readline()) in Command-line

Instead of asking, you can pass arguments, parameters, to the script.

Instead of

scrpt.R:

r=readline(prompt="number: ")
print(sqrt(r))

You can do

scrpt.R:

args<-commandArgs(TRUE)
print(sqrt(as.numeric(args[1])))

And at the command window,

c:\R\ax>Rscript scrpt.R 2 arg2 arg3
[1] 1.414214

Switch R script from non-interactive to interactive

Can you just fire up R and source the file instead?

R
source("script.R")

How to include interactive input in script to be run from the command line

Try this:

cat("What's your name? ")
x <- readLines(file("stdin"),1)
print(x)

Hopefully some variant of that works for you.

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

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.

Run R script from command line

If you want the output to print to the terminal it is best to use Rscript

Rscript a.R

Note that when using R CMD BATCH a.R that instead of redirecting output to standard out and displaying on the terminal a new file called a.Rout will be created.

R CMD BATCH a.R
# Check the output
cat a.Rout

One other thing to note about using Rscript is that it doesn't load the methods package by default which can cause confusion. So if you're relying on anything that methods provides you'll want to load it explicitly in your script.

If you really want to use the ./a.R way of calling the script you could add an appropriate #! to the top of the script

#!/usr/bin/env Rscript
sayHello <- function(){
print('hello')
}

sayHello()

I will also note that if you're running on a *unix system there is the useful littler package which provides easy command line piping to R. It may be necessary to use littler to run shiny apps via a script? Further details can be found in this question.

Rscript detect if R script is being called/sourced from another script

EDIT

Okay, this is a LOT more like python's __name__ trick. (Previous answer below, kept for historical reasons.)

function1 <- function(etc,etc) {}
function2 <- function(etc,etc) {}

if (sys.nframe() == 0L) {
library(optparse)
# ...
}

It is about as minimalist as one could hope for, does not require the sourceing script to know anything about it, and seems to work well even when nested.

Other possible mechanisms could be used (additional functions required) by looking at script names, per Rscript: Determine path of the executing script. Many plausible (some really good) solutions exist there, but they all require a pre-defined function not defined in a base package (or non-trivial code included in the script to be sourced). If you want to "assume package X is installed", then your script becomes potentially non-portable.


(Previous answer, I suggest you use above.)

I'll throw this out as a hack ... it's only slightly less janky than your workaround, but it relies on the calling script knowing something of what the called script is testing for.

If the calling script sets a variable:

BEING_SOURCED_FROM_SOMEWHERE <- TRUE

then the called script can check for it:

function1 <- function(etc,etc) {}
function2 <- function(etc,etc) {}

if (! exists("BEING_SOURCED_FROM_SOMEWHERE")) {
library(optparse)
# ...
}

I don't like it. It isn't as flexible as python's

if __name__ == "__main__":
import optparse
# ...

But I think I dislike it less than your use of save and load for function definitions.

How do I test if R is running as Rscript?

You could use interactive to test if R is running in interactive mode. interactive will return FALSE under Rscript and TRUE under (most?) GUIs.



Related Topics



Leave a reply



Submit