center <- function(x, type = c("mean", "median", "trimmed")) {
type <- match.arg(type)
print(type)
switch(type, mean = mean(x), median = median(x), trimmed = mean(x, trim = 0.1))
}
center(1:3,"t")
[1] "trimmed"
2
center(1:3,"me")
Error in match.arg(type): 'arg' should be one of "mean", "median", "trimmed"
Traceback:
1. center(1:3, "me")
2. match.arg(type) # at line 2 of file <text>
3. stop(gettextf("'arg' should be one of %s", paste(dQuote(choices),
. collapse = ", ")), domain = NA)
center(1:3,"mea")
[1] "mean"
2
match.arg可以用来做类型匹配,具体到上面的案例:
- 候选参数中,只有trimmed是t开头的,所以type参数传错了,也可以正常执行
- 而me有两种可能,函数报错
- 第三个很清晰了,不赘述
2019-12-20 于南京市江宁区九龙湖