Is there a way to know if an R script is running directly or within another script?

r

Solution

Not a direct answer to your question, but a related one is to look at the `interactive` function. This function will return `TRUE` if R believes that you are in an interactive session and it is reasonable to assume a person is available to answer questions, it will return `FALSE` if running in BATCH mode and it is fairly certain that there are no humans (or aliens, intelligent animals, etc.) to answer questions.

Not exactly what you were asking, but it may be helpful for deciding whether to prompt for information.

Problem

I am using R studio. Is there a way to know if an R script is running directly either by the source command in the console) or within another script. ie. another script is sourced and this has the call to the first script. This can be useful to prompt for some values in some cases. What I am doing now is to set a variable to true or false and within the script I check for that variable. This works but an automatic way is better. Thanks for your time. EDIT: More info Let's say I have an independent script that runs fine as is, but this script is part of a process to run after another script finished. If I have to run both, I can run the first, then the second; but also I have the chance just to run the second. What I am asking is if there is a way to (in the second script) to verify if this second was called from the first or no. Take a look at his simple examples (inspired by the answer from Greg Snow). First the file I call in Rstudio ``` # scripta.R writeLines("script A") if (interactive()) writeLines("interactive: true") else writeLines("interactive false") source("scriptb.r") writelines("after B") ``` Then the file being sourced ``` # scriptb.R writeLines("script B") if (interactive()) writeLines("interactive: true") else writeLines("interactive false") writeLines("end B") ``` The result in Rstudio is ``` script A interactive: true script B interactive: true end B after B ``` I like to have something like ``` script A interactive: true script B interactive: false end B after B ``` I hope now is more clear. Thanks

Original source