13

I have code in a single R file that I want to be able to source (i.e., to define my functions etc.) within RStudio during development, and also run using the #! /usr/bin/env Rscript syntax via the command line (actually, using Hadoop). For the latter, I need the last thing that Rscript does to be to kick off the analysis (i.e., using a call to a main() function). For the former, I don't want my main() function called. I'd like to be able to test if the code is running within Rscript (or, alternatively, within RStudio), so that I can either execute main() or not. Is this possible, please?

One solution would be to break my code into multiple files, but I'd rather avoid this if possible (to make the Hadoop stuff slightly easier).

Thanks in advance.

2
  • Thanks for mentioning RStudio - I wasn't aware of this software program until now, but I'm glad I 'found' it. Commented Mar 20, 2012 at 12:43
  • No worries, Jura25. It's much less mature than the Matlab or Mathematica front ends, but does the job very well for R. Commented Mar 20, 2012 at 13:43

1 Answer 1

15

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Joshua. I can't believe I didn't find this…
After 9+ years I still find this useful. BTW interactive() returns a TRUE even when used inside a file that is sourced, in Rstudio. Is that expected?
@LazarusThurston: yes, that's expected. RStudio is an interactive console, so it's TRUE even if you source() a file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.