Alex
Alex

Reputation: 19793

correct braces placement in := within data.table

Here is an example of a problem I am having. Am I misusing or is this a bug?

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)]

Upvotes: 9

Views: 1126

Answers (1)

Ricardo Saporta
Ricardo Saporta

Reputation: 55340

not a bug, it's just that the ordering of the braces should be different:

That is, use the braces to wrap only the RHS argument in `:=`(LHS, RHS)

Example:

# 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

However, more succinctly and naturally:

you are probably looking for this:

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


Update from Matthew

Exactly. Using := in other incorrect ways gives this (long) error :

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.

but not in the case that the question showed, giving just :

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

I've just changed this in v1.8.9. Both these incorrect ways of using := now give a more succinct error :

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.

and we'll embellish ?":=". Thanks @Alex for highlighting!

Upvotes: 14

Related Questions