data.tableassigne-by-reference`:=`的标准形式和功能形式的不同结果 [英] different results for standard form and functional form of data.table assigne-by-reference `:=`
问题描述
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)
.
这篇关于data.tableassigne-by-reference`:=`的标准形式和功能形式的不同结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!