如何在data.table包中实现列表构造函数的点(。)别名? [英] How is dot (.) alias for list constructor implemented in data.table package?

查看:52
本文介绍了如何在data.table包中实现列表构造函数的点(。)别名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道 list 构造函数的点别名()如何在<$中实现c $ c> data.table 包。为了清楚起见,我正在考虑此功能:

I wonder how is is the dot alias (.) for the list constructor function implemented in the data.table package. Just to be clear I am thinking about this functionality:

library(data.table)
D = data.table(iris)
x1 = D[, .(Sepal.Length, Sepal.Width)]    # dot alias
x2 = D[, list(Sepal.Length, Sepal.Width)] # standard name
identical(x1, x2)    # TRUE

我试图在源代码中找到它github,但是它太密集了,我无法在任何合理的时间内理解它。

I tried to find it in the source code on github, but it is too dense for me to understand it in any reasonable amount of time.

编辑。
我知道可以通过定义一个别名来轻松实现,例如:。 <-列表。 <-函数(...)列表(...)。但是,这并不是我要找的东西。我想定义这样的别名,因此它仅在给定的函数/方法的上下文中起作用。

EDIT. I know this can be easily done by defining an alias like: . <- list or . <- function(...) list(...). However, this is not exactly what I am looking for. I want to define such an alias, so it only works in the context of a given function/method.

示例。

L <- .(1)   # This throws error
L <- func(.(1)) # This works

实际上,我可以使用 rlang 工具进行整洁的评估,得到想要的东西。下面是一个简单的示例。

Actually I can get what I want using the rlang tools for tidy evaluation. Below is a simple example.

library(rlang)
func <- function(...) {
    . <- list
    eval_tidy(enexpr(x))
}
x1 <- func(.(1))
x2 <- list(1)
identical(x1, x2)   # TRUE

所以我想知道如何在 data.table 特别是,因为它的开发时间早于 rlang

So I wonder how this kind of functionality is implemented in the data.table specifically, since it was developed a way earlier than rlang?

推荐答案

data.table在计算表达式之前会替换表达式中的点。

data.table replaces the dot in expressions before they are evaluated. It uses computing on the language.

相关功能为 replace_dot_alias (请注意,重复使用此功能意味着您需要遵守data.table的许可证):

The relevant function is replace_dot_alias (note that reusing this function means that you need to conform to data.table's license):

replace_dot_alias = function(e) {
  # we don't just simply alias .=list because i) list is a primitive (faster to iterate) and ii) we test for use
  # of "list" in several places so it saves having to remember to write "." || "list" in those places
  if (is.call(e) && !is.function(e[[1L]])) {
    # . alias also used within bquote, #1912
    if (e[[1L]] == 'bquote') return(e)
    if (e[[1L]] == ".") e[[1L]] = quote(list)
    for (i in seq_along(e)[-1L]) if (!is.null(e[[i]])) e[[i]] = replace_dot_alias(e[[i]])
  }
  e
}

用法示例:

expr <- quote(.(a = b, c = .(sum(d))))
replace_dot_alias(expr)
#list(a = b, c = list(sum(d)))

然后执行修改后的表达式。

The modified expression is then executed.

这篇关于如何在data.table包中实现列表构造函数的点(。)别名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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