forked from chr1swallace/random-functions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
getArgs.R
59 lines (55 loc) · 1.53 KB
/
getArgs.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
##' commandArgs parsing
##'
##' return a named list of command line arguments
##'
##' Usage:
##' call the R script thus
##' ./myfile.R --args --myarg=something
##' or
##' R CMD BATCH --args --myarg=something myfile.R
##'
##' Then in R do
##' myargs <- getArgs()
##' and myargs will be a named list
##' > str(myargs)
##' List of 2
##' $ file : chr "myfile.R"
##' $ myarg: chr "something"
##'
##' @title getArgs
##' @param verbose print verbage to screen
##' @param defaults a named list of defaults, optional
##' @param numeric names of arguments that should be converted from character to numeric, optional
##' @return a named list
##' @author Chris Wallace
getArgs <- function(verbose=FALSE, defaults=NULL, numeric=NULL) {
myargs <- gsub("^--","",commandArgs(TRUE))
setopts <- !grepl("=",myargs)
if(any(setopts))
myargs[setopts] <- paste(myargs[setopts],"=notset",sep="")
myargs.list <- strsplit(myargs,"=")
myargs <- lapply(myargs.list,"[[",2 )
names(myargs) <- lapply(myargs.list, "[[", 1)
## logicals
if(any(setopts))
myargs[setopts] <- TRUE
## defaults
if(!is.null(defaults)) {
defs.needed <- setdiff(names(defaults), names(myargs))
if(length(defs.needed)) {
myargs[ defs.needed ] <- defaults[ defs.needed ]
}
}
## numerics
if(!is.null(numeric)) {
numeric <- intersect(numeric, names(myargs))
if(length(numeric))
myargs[numeric] <- lapply(myargs[numeric], as.numeric)
}
## verbage
if(verbose) {
cat("read",length(myargs),"named args:\n")
print(myargs)
}
myargs
}