How to pass command line argument when using source()
There really is no notion of a "command line" for the R parser. It executes a complete function call if it finds one in the "do_something.r" file before moving on to any expression that might follow the correct separator, a semi-colon. The parser will not pass the trailing expression to the evaluator until the sourced code is completed, so will not "see" any expression that follows. You have two choices:
To do this from the RGui console you need to do something like:
val <- 10; source("do_something.r") # set value first, then `source`
To use a "real" command line (not from the RGui), try this (assuming that the code in do_something.r will access a variable named val
):
Rscript do_something.r -e 'val <- 10'
See ?Rscript
for more details and examples.
Is it possible to read commandline arguments when running R interactively?
If you pass the command line arguments like this: R --args 1 2
, then you can access them as follows:
> args = commandArgs(trailingOnly=TRUE)
> args
[1] "1" "2"
Is it possible to specify command line parameters to R-script in RStudio?
I know this question is old and the link below is old, but it answers the question. No, it's not possible (or wasn't as of Jan 29, 2012) to access command line arguments from RStudio.
Link
https://support.rstudio.com/hc/communities/public/questions/200659066-Accessing-command-line-options-in-RStudio?locale=en-us
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 source
ing 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 to pass in function parameters for an R file when run from terminal?
commandArgs
function returns a character vector with the arguments passed to the command line (trailingOnly = TRUE
removes the "RScript helpme.R"
part).
In your case :
args <- commandArgs(trailingOnly = TRUE)
# parse your command line arguments
x <- as.numeric(args[1]) # args[1] contains "100"
y <- as.numeric(args[2]) # args[2] contains "10"
# ...continue with your script here
Related Topics
How to Match by Nearest Date from Two Data Frames
Randomly Insert Nas into Dataframe Proportionaly
Conditional Binary Join and Update by Reference Using the Data.Table Package
Is There a Logical Way to Think About List Indexing
Add Percentage Labels to a Stacked Barplot
Difference Between If() and Ifelse() Functions
Counting Number of Instances of a Condition Per Row R
How to Stack Error Bars in a Stacked Bar Plot Using Geom_Errorbar
Ggplot2: Connecting Points in Polar Coordinates with a Straight Line 2
Aggregate and Reshape from Long to Wide
Return Data Subset Time Frames Within Another Timeframes
Dplyr Issues When Using Group_By(Multiple Variables)
Shiny: Passing Input$Var to Aes() in Ggplot2
Change Day of the Month in a Date to First Day (01)
Calling an R Function Using Inline and Rcpp Is Still Just as Slow as Original R Code