数据的标准形式和功能形式的结果不同. [英] different results for standard form and functional form of data.table assigne-by-reference `:=`

查看:75
本文介绍了数据的标准形式和功能形式的结果不同.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在data.tabel的引用中,按功能形式标准中的:=分配似乎略有不同.

There seems to be a minor difference between data.tabel's assignment by reference := in the standard to the functinal form.

标准形式将RHS强制为矢量,而功能形式则不是. 详细信息,但据我所知没有记录.

Standard form coerces RHS to vector, the functional form does not. A detail, but not documented as I believe.

library(data.table)
dt <- data.table(a = c('a','b','c'))
v <- c('A','B','C')
l <- list(v)

all.equal(copy(dt)[, new := v], copy(dt)[, `:=` (new = v)])
# [1] TRUE
all.equal(copy(dt)[, new := l], copy(dt)[, `:=` (new = l)])
# [1] "Datasets have different column modes. First 3: new(character!=list)"

copy(dt)[, new := l][]
#    a new
# 1: a   A
# 2: b   B
# 3: c   C

copy(dt)[, `:=` (new = l)][]
#    a   new
# 1: a A,B,C
# 2: b A,B,C
# 3: c A,B,C

这是我最初问这个问题的主要方法.

This is a major Edit of how I asked this question originally.

推荐答案

这是一个很好的问题,涉及到有关:=运算符的设计决策.

This is very good question that touches design decision about := operator.

对于使用:=作为运算符的简单调用,例如col := val,我们决定将val自动包装到列表中.做出此决定是为了使用户更方便地分配单个列.

For simple calls using := as an operator, like col := val, we decided to wrap val into a list automatically. This decision was made to make it more convenient for users to assign single column.

使用函数调用形式时,":="(col = val)我们不再将val包装到列表中.它已经是扩展形式. :=充当list的别名,但会就地更新 .您始终可以通过将:=更改为list(或.)(如.(col = val))来检查更新的列.

When you are using function call form, ":="(col = val) we are not wrapping val into list anymore. It is extended form already. := behaves as an alias to list but updating in-place. You can always check what will be the updated column by changing := into list (or .) like .(col = val).

即使将:=用作运算符,您仍必须提供RHS作为正在创建2个以上列的列表,即c("col1","col2") := list(val1, val2).

Not that even when using := as an operator, you still have to provide RHS as list of you are creating 2+ columns, c("col1","col2") := list(val1, val2).

这篇关于数据的标准形式和功能形式的结果不同.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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