R语言match.arg函数

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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值