Why does data.table `:=` work differently with or without `by` when there are more return values than columns to assign?

Viewed 440

This is a follow up question to this one Why the new columns created with := and tstrsplit are different with or without `by` argument?.

Compare these two pieces of code:

library(data.table)

DT <- data.table(col = c('a', 'a_b', 'a_b_c'))

DT[, c('col1', 'col2') := tstrsplit(col, '_')]

which produces the following error:

Error in '[.data.table'(DT, , ':='(c("col1", "col2"), tstrsplit(col, "_"))) : Supplied 2 columns to be assigned 3 items. Please see NEWS for v1.12.2.

An error that I understand perfectly. But, I do not get why the next piece of code does not produce an error:

library(data.table)

DT <- data.table(col = c('a', 'a_b', 'a_b_c'))

DT[, c('col1', 'col2') := tstrsplit(col, '_'), by = .(col)]
DT

Output:

     col col1 col2
1:     a    a    a
2:   a_b    a    b
3: a_b_c    a    b
0 Answers
Related