[R] improving match.args()
oehl_list@gmx.de
oehl_list at gmx.de
Thu May 2 14:33:15 CEST 2002
Here is a suggestion for improving match.arg()
Comments welcome.
Best
Jens Oehlschlägel
# up to now match.arg() works as
t1 <- function( param = c("default", "alternative1", "alternative2") ){
param <- match.arg(param)
param
}
# and
args(t1)
# > function (param = c("default", "alternative1", "alternative2"))
# misleadingly tells us the default of param would be a vector of length 3
# the modified version of match.args() works as before, but additionally
allows us to be more clear about our parameter default:
t1 <- function( param = c("default", "alternative1", "alternative2")[1] ){
param <- match.arg1(param)
param
}
# so
args(t1)
# > function (param = c("default", "alternative1", "alternative2")[1])
# gives the desired clarity
# of course, if we have only one default extracted by [1] the following
t1 <- function( param = letters[1] ){
param <- match.arg1(param)
param
}
# will allow too many values, however, with only one default, isn't using
match.arg() nonsense anyhow?
match.arg1 <- function (arg, choices)
{
if (missing(choices)) {
formal.arg <-
formals(sys.function(sys.parent()))[[deparse(substitute(arg))]]
if (length(formal.arg)==3 && formal.arg[[1]]=="[" &&
formal.arg[[3]]==1)
formal.arg <- formal.arg[[2]]
choices <- eval(formal.arg)
}
if (all(arg == choices))
return(choices[1])
i <- pmatch(arg, choices)
if (is.na(i))
stop(paste("ARG should be one of", paste(choices, collapse = ", "),
sep = " "))
if (length(i) > 1)
stop("there is more than one match in match.arg")
choices[i]
}
--
GMX - Die Kommunikationsplattform im Internet.
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !) To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
More information about the R-help
mailing list