Skip to content

[bug] Changing columns by reference changes previously stored column names #3316

Closed

Description

@jeroenvdhoven

I noticed an error when saving the column names of a data.table in a variable. After storing the column names, adding a column by reference to the data.table from which the column names were taken would change the variable containing the column names. It seems that when you're making a copy of the colnames() result this doesn't happen anymore (see below the bug example) and this also doesn't happen when using data.frame. I tried this on a fresh install and it still occurs.

Example

# data.table
library(data.table)
N <- 10
x <- data.table(
    a = seq_len(N),
    b = seq_len(N) + 5
)


# Bug flow:
cols <- colnames(x)
print(cols)
# Gives: a b
x[, d := seq_len(N) - 5]
print(cols)
# Gives: a b d

# Works as expected:
cols <- colnames(x)[]
print(cols)
# Gives: a b d
x[, e := seq_len(N) - 5]
print(cols)
# Gives: a b d


# data.frame example
N <- 10
x <- data.frame(
    a = seq_len(N),
    b = seq_len(N) + 5
)
cols <- colnames(x)

print(cols)
# Gives: a b
x$d = 5
print(cols)
# Gives: a b

SessionInfo()

R version 3.5.2 (2018-12-20)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS Mojave 10.14.2

Matrix products: default
BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] data.table_1.12.0

loaded via a namespace (and not attached):
[1] compiler_3.5.2 tools_3.5.2    packrat_0.5.0 

Activity

  1. mattdowle commented on Jan 26, 2019

    @mattdowle
    Member

    This is correct behaviour of the by-reference operators := and set*. Please see their manual pages and ?copy too. If you do v=DT$colA and then do := on colA you'll see v changes too. There are quite a few stack overflow answers about it as well. When using by-reference operators you need to explicity use copy when you want a copy.

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions