The code below illustrates my issue:
> A <- data.table(value=1)
> A_cols <- names(A)
> A[,new_value:=2]
> A_cols
[1] "value" "new_value"
Here the variable A_cols
was indirectly modified when the :=
modifier was used to modify the data.table
A
. This was unexpected for me.
I understand why this use of :=
would modify the value pointed to by a data.table
assigned via something like B <- A
, but that isn't what's happening here. The variable A_cols
is the result of applying a function to my data.table
.
Also, this behavior appears to be inconsistent since
> A <- data.table(value=1)
> A_num_cols <- ncol(A)
> A[,new_value:=2]
> A_num_cols
[1] 1
leaves the variable A_num_cols
unaltered.
I wondered if the code behind names
is the culprit, but there is no information in the documentation that would give a clue as to why this behavior should be expected.
Is this indeed expected, and if so, are there any explanations as to the philosophy behind this and why it seems to be applied inconsistently?