9

这是我遇到的问题的一个例子。我是在滥用还是这是一个错误?

require(data.table)
x <- data.table(a = 1:4)

# this does not work
x[ , {b = a + 3; `:=`(c = b)}]
# Error in `:=`(c = b) : unused argument(s) (c = b)

# this works fine
x[ ,`:=`(c = a + 3)]
4

1 回答 1

13

不是错误,只是大括号的顺序应该不同:

也就是说,使用大括号仅将RHS参数包装在 `:=`(LHS, RHS)

例子:

# sample data
x <- data.table(a = 1:4)

# instead of: 
x[ , {b = a + 3; `:=`(c, b)}]   # <~~ Notice braces are wrapping LHS AND RHS

# use this: 
x[ , `:=`(c,  {b = a + 3; b})]  # <~~ Braces wrapping only RHS

x
#    a c
# 1: 1 4
# 2: 2 5
# 3: 3 6
# 4: 4 7

然而,更简洁自然:

你可能正在寻找这个:

 x[ , c := {b = a + 3; b}]


马修更新

确切地。以:=其他不正确的方式使用会产生这个(长)错误:

x := 1
# Error: := is defined for use in j only, and (currently) only once; i.e.,
# DT[i,col:=1L] and DT[,newcol:=sum(colB),by=colA] are ok, but not
# DT[i,col]:=1L, not DT[i]$col:=1L and not DT[,{newcol1:=1L;newcol2:=2L}].
# Please see help(":="). Check is.data.table(DT) is TRUE.

但不是在问题显示的情况下,只给出:

x[ , {b = a + 3; `:=`(c = b)}]
# Error in `:=`(c = b) : unused argument(s) (c = b)

我刚刚在 v1.8.9 中对此进行了更改。这两种不正确的使用方式:=现在都给出了更简洁的错误:

x[ , {b = a + 3; `:=`(c = b)}]
# Error in `:=`(c = b) : 
#   := and `:=`(...) are defined for use in j only, in particular ways. See 
#   help(":="). Check is.data.table(DT) is TRUE.

我们会修饰?":="。感谢@Alex 强调!

于 2013-03-31T20:07:52.177 回答