match.arg根据选项指定的候选值表匹配字符arg。
Usage
match.arg(arg, choices, several.ok =FALSE)
Arguments
arg | a character vector (of length one unless several.ok is TRUE) or NULL which means to take choices[1]. |
choices | a character vector of candidate values, often missing, see ‘Details’. |
several.ok | logical specifying if arg should be allowed to have more than one element. |
#### R match.arg函数
require(stats)
center <- function(x, type = c("mean", "median", "trimmed")) {
type <- match.arg(type)
switch(type,
mean = mean(x),
median = median(x),
trimmed = mean(x, trim = .1))
}
x <- rcauchy(10)
#R switch() 用法
#n <- 2
#switch (n,"first","second","third","fourth")
#n的值为2,则switch函数根据传入的值2,输出列表中的第2个值
#若switch()中的参数list是有名定义时,则当expr等于元素名时,返回变量名对应的值,否则没有返回值。
# 从左到右匹配,找到参数并处理
center(x, "tri")
center(x, "t")
center(x, "med")
center(x, "mea")
center(x, "mean")
# match.arg(arg, choices, several.ok = FALSE)
type <- c("mean", "median", "trimmed")
match.arg(c('med','tri'),
c("mean", "median", "trimmed"),
several.ok = TRUE)
match.arg(c("gauss", "rect", "ep"),
c("gaussian", "epanechnikov", "rectangular", "triangular"),
several.ok = TRUE)
# 如果arg中每一个参数,不是和choices唯一匹配的将不返回结果(不报错)
match.arg(arg = c("gauss", "ar"),
choices = c("gaussian", "epanechnikov", "rectangular", "triangular"),
several.ok = TRUE)