R:为什么:=允许作为中缀运算符? [英] R: Why is := allowed as an infix operator?

查看:131
本文介绍了R:为什么:=允许作为中缀运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经遇到了流行的 data.table 包,有一件事特别感激我。它有一个就地赋值运算符

I have come across the popular data.table package and one thing in particular intrigued me. It has an in-place assignment operator


:=

:=

这没有在基础R中定义。事实上,如果你没有加载 data.table 包,它会产生一个错误,如果你试过使用它(例如 a:= 2 )并显示以下消息:

This is not defined in base R. In fact if you didn't load the data.table package, it would have raised an error if you had tried to used it (e.g., a := 2) with the message:


错误:找不到函数:=

:= 工作?为什么R让你定义:= 为中缀运算符,而每个其他中缀函数必须由 %% 例如

Also, why does := work? Why does R let you define := as infix operator while every other infix function has to be surrounded by %%, e.g.

`:=` <- function(a, b) {
   paste(a,b)
}

"abc" := "def"

它并不意味着用于定义中缀函数的%function.name%的替代语法。是 data.table 利用R的一些解析怪癖吗?这是一个黑客?它会在未来修补吗?

Clearly it's not meant to be an alternative syntax to %function.name% for defining infix functions. Is data.table exploiting some parsing quirks of R? Is it a hack? Will it be "patched" in the future?

推荐答案

这是基础R解析器识别的东西,似乎解析为左分配(至少在条款或顺序操作等)。有关详细信息,请参见 C源代码

It is something that the base R parser recognizes and seems to parse as a left assign (at least in terms or order of operations and such). See the C source code for more details.

as.list(parse(text="a:=3")[[1]])
# [[1]]
# `:=`
# 
# [[2]]
# a
# 
# [[3]]
# [1] 3

至于我可以告诉它是无记录的关心)。但是它是一个函数/运算符,你可以改变

As far as I can tell it's undocumented (as far as base R is concerned). But it is a function/operator you can change the behavior of

`:=`<-function(a,b) {a+b}
3 := 7
# [1] 10

正如你所看到的,:部分本身并没有什么特别的。它恰好是复合令牌的开始。

As you can see there really isn't anything special about the ":" part itself. It just happens to be the start of a compound token.

这篇关于R:为什么:=允许作为中缀运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆