反引号在 R 中有什么作用?

What do backticks do in R?

我想了解反引号在 R 中的作用。

据我所知,R 的 ?Quotes 文档页面中并未对此进行解释。

例如,在 R 控制台:

"[["
# [1] "[["
`[[`
# .Primitive("[[")

它似乎返回等同于:

get("[[")

它们相当于逐字逐句。例如...试试这个:

df <- data.frame(20a=c(1,2),b=c(3,4))

给出错误

df <- data.frame(`20a`=c(1,2),b=c(3,4))

不报错

这是一个使用不当词汇的不完整答案:反引号可以向 R 表明您正在以非标准方式使用函数。例如,这里是 [[ 列表子集函数的用法:

temp <- list("a"=1:10, "b"=rnorm(5))

提取元素一,通常的方法

temp[[1]]

使用[[函数提取元素一

`[[`(temp,1)

一对反引号是指代保留或非法的名称或符号组合的一种方式。保留是像 if 这样的词是语言的一部分,而非法包括像 c a t 这样的非句法组合。这两个类别,保留的和非法的,在 R 文档中被称为 non-syntactic names.

因此,

`c a t` <- 1 # is valid R

> `+` # is equivalent to typing in a syntactic function name
function (e1, e2)  .Primitive("+")

正如评论者提到的,?Quotes 确实包含一些关于反引号的信息,在 Names and Identifiers:

Identifiers consist of a sequence of letters, digits, the period (.) and the underscore. They must not start with a digit nor underscore, nor with a period followed by a digit. Reserved words are not valid identifiers.

The definition of a letter depends on the current locale, but only ASCII digits are considered to be digits.

Such identifiers are also known as syntactic names and may be used directly in R code. Almost always, other names can be used provided they are quoted. The preferred quote is the backtick (`), and deparse will normally use it, but under many circumstances single or double quotes can be used (as a character constant will often be converted to a name). One place where backticks may be essential is to delimit variable names in formulae: see formula

这篇散文有点难以解析。这意味着 R 要将标记解析为名称,它必须是 1) 字母数字序列、句点和下划线,2) 不是语言中的保留字。否则,要解析为名称,必须使用反引号。

另请查看 ?Reserved:

Reserved words outside quotes are always parsed to be references to the objects linked to in the 'Description', and hence they are not allowed as syntactic names (see make.names). They are allowed as non-syntactic names, e.g.inside backtick quotes.

此外,Advanced R 有一些反引号在 expressions, environments, and functions 中如何使用的例子。