简体   繁体   English

与match.arg()匹配的数字参数

[英]Numeric argument matching with match.arg()

In match.arg() , why can the choices argument be numeric but the arg argument value cannot? match.arg() ,为什么choices参数是数字但是arg参数值不能? Is the function not supposed to be used to match numeric arguments? 该函数不应该用于匹配数字参数吗?

The documentation file for match.arg shows the following, but makes no mention of numeric values match.arg的文档文件显示以下内容,但未提及数值

choices a character vector of candidate values 选择候选值的字符向量

Ok, but it's not in the following example. 好的,但它不在以下示例中。

f <- function(year){
    match.arg(year, choices = 1995:2005)
}

f(2000)
# Error in match.arg(year, 1995:2005) : 
#  'arg' must be NULL or a character vector

g <- function(year){
   match.arg(as.character(year), choices = 1995:2005)
}

g(2000)
# [1] 2000

So a character string just matched an numeric value...interesting. 所以一个字符串恰好匹配一个数值...有趣。

My purpose for using this function is to determine if the user-entered year is a member of a large vector of years, which is not necessarily a sequence (some are missing). 我使用此函数的目的是确定用户输入的year是否是多年的大向量的成员,这不一定是序列(有些是缺失的)。

Also note that year = NULL won't work for me here, because that would mean the default year would be 1871 in my actual data, which I don't want. 另请注意, year = NULL对我来说不起作用,因为这意味着我的实际数据中的默认年份是1871,这是我不想要的。

Snippet from match.arg 来自match.arg片段

else if (!is.character(arg)) 
        stop("'arg' must be NULL or a character vector")

with no attempt at coercion to a character string. 没有试图胁迫字符串。

From ?match.arg 来自?match.arg

Matching is done using pmatch , so arg may be abbreviated. 匹配是使用pmatch完成的,因此arg可以缩写。

From the ?pmatch Arguments section 来自?pmatch Arguments部分

x X
the values to be matched: converted to a character vector by as.character. 要匹配的值:通过as.character转换为字符向量。 Long vectors are supported. 支持长向量。

Therefore, with match.arg , a user cannot use a numeric arg but can use a numeric choices vector. 因此,使用match.arg ,用户不能使用数字arg但可以使用数字choices向量。 It has been my experience that 5 is not the same as "5" . 根据我的经验, 5"5"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM