Skip to content

updating data.table by reference has side effect of altering other non-data.table objects  #5756

Open

Description

@domwoolf

If we assign a data.table's names to an R variable, then update the data.table columns by reference (with :=) the R object that stored the original names also (surprisingly) gets updated by reference. This does not seem to be desired behaviour to me. Especially as the use case where I discovered this was when trying to save the column names before alteration for later use.

Minimal example:

x = as.data.table(matrix(nrow = 10, ncol = 10))
xnames = names(x)
xnames
# [1] "V1"  "V2"  "V3"  "V4"  "V5"  "V6"  "V7"  "V8"  "V9"  "V10"

x[, (paste0('V', 3:7)) := NULL]
xnames
# [1] "V1"  "V2"  "V8"  "V9"  "V10"

x[, newcol := 1]
xnames
# [1] "V1"     "V2"     "V8"     "V9"     "V10"    "newcol"

setcolorder(x, 'newcol')
xnames
# [1] "newcol" "V1"     "V2"     "V8"     "V9"     "V10" 

We can work around this issue by using xnames = copy(names(x)), however the fact that updating a data.table by reference has this side effect is probably best avoided in the first place.

Activity

  1. AngelFelizR commented on Nov 24, 2023

    @AngelFelizR
    Contributor

    I agree, that behavior can be problematical.

  2. jangorecki commented on Nov 24, 2023

    @jangorecki
    Member

    isn't this documented enough? did you look for duplicated issues before reporting?

    I bet there is code that relies on that behavior and we cannot really change that without incrementing data.table version to 2.0.0

  3. jangorecki commented on Nov 24, 2023

    @jangorecki
    Member
  4. added this to the 2.0.0 milestone on Nov 24, 2023
  5. added
    breaking-change
    and removed on Jul 22, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    breaking-change

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions