Skip to content

Instantly share code, notes, and snippets.

@yoavram
Created October 29, 2012 14:47
Show Gist options
  • Save yoavram/3973953 to your computer and use it in GitHub Desktop.
Save yoavram/3973953 to your computer and use it in GitHub Desktop.
Override default parameters in R from command line with 4 lines of code
# Override default parameters in R from command line with 4 lines of code (the numbered lines)
# Run from command line:
# R --slave -f demo.r --args p.success=0.9 num.of.tests=1000
# R --slave -f demo.r --args p.success=0.5 num.of.tests=10000
# R --slave -f demo.r --args p.success=0.3 num.of.tests=10
#
# Created 29/10/12 by Yoav Ram (www.yoavram.com), licenced under the WTFPL free software license
# default parameter values
num.of.tests <- 100
p.success <- 0.5
# code to change the defaults
args = commandArgs(T) # 1
cat("Changing default parameters with command line arguments:\n")
for (arg in args) { # 2
cat(arg,"\n")
# the next line is the one that evaluates the input and overrides the default
eval(parse(text=arg)) # 3
} # 4
# the actual program using the parameters
successes <- rbinom(n=1, size=num.of.tests, prob=p.success)
cat(sprintf("Number of successes (N=%d, p=%.2f): %d\n", num.of.tests, p.success, successes))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment