Conversation
joshhwuu
reviewed
Jun 8, 2026
|
|
||
| ### d) Side effects and testing | ||
|
|
||
| Because `:=` modifies by reference, changes are cumulative. If the same *data.table* is reused—for example, in a loop or when using `test()` with multiple `optimization` levels—subsequent runs will start with the modified table from the previous run. Use `copy()` to ensure each run starts with the same data. |
jangorecki
reviewed
Jun 9, 2026
| \code{DT[a > 4, b := c]} is different from \code{DT[a > 4][, b := c]}. The first expression updates (or adds) column \code{b} with the value \code{c} on those rows where \code{a > 4} evaluates to \code{TRUE}. \code{X} is updated \emph{by reference}, therefore no assignment needed. Note that this does not apply when \code{i} is missing, i.e. \code{DT[]}. | ||
|
|
||
| The second expression on the other hand updates a \emph{new} \code{data.table} that's returned by the subset operation. Since the subsetted data.table is ephemeral (it is not assigned to a symbol), the result would be lost; unless the result is assigned, for example, as follows: \code{ans <- DT[a > 4][, b := c]}. | ||
| Note that \samp{:=} modifications are cumulative. When reusing a \code{data.table} in loops or multi-level tests, use \code{\link{copy}} to ensure a fresh state. |
Member
There was a problem hiding this comment.
I don't think cumulative is good word here. In-place changing it's input seems to be more precise.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
closes #7409
Documented
:=side effects in repeated execution acrossdatatable-reference-semantics.Rmd,assign.Rd, andtest.Rd.hi @ben-schwen, whenever you have a chance, could you please take a look at this PR.
thanks