Skip to content

Using names(obj) <- names(dt) could be problematic #5079

@renkun-ken

Description

@renkun-ken

Since set* and := set by reference, it seems to alter the names() character vector by reference too. Then the assignment like names(obj) <- names(dt) might lead to unexpected error.

Consider the following example:

library(data.table)

dt <- data.table(x = 1:10, y = 10:1)
dt

p <- list(1, 2)
names(p) <- names(dt)

p

dt[, z := 1:10]

p
names(p)

p <- list(1, 2, 3)
names(p) <- names(dt)
p

setcolorder(dt, c("z", "y", "x"))
p
> library(data.table)
> dt <- data.table(x = 1:10, y = 10:1)
> dt
        x     y
    <int> <int>
 1:     1    10
 2:     2     9
 3:     3     8
 4:     4     7
 5:     5     6
 6:     6     5
 7:     7     4
 8:     8     3
 9:     9     2
10:    10     1

> p <- list(1, 2)
> names(p) <- names(dt)
> p
$x
[1] 1

$y
[1] 2


> dt[, z := 1:10]
'names' attribute [3] must be the same length as the vector [2]
> p
$x
[1] 1

$y
[1] 2

'names' attribute [3] must be the same length as the vector [2]
> names(p)
[1] "x" "y" "z"
'names' attribute [3] must be the same length as the vector [2]
> p <- list(1, 2, 3)
> names(p) <- names(dt)
> p
$x
[1] 1

$y
[1] 2

$z
[1] 3

> setcolorder(dt, c("z", "y", "x"))
> p
$z
[1] 1

$y
[1] 2

$x
[1] 3

I don't see a "don't do this" in wiki and the only thing about this is in the vignette Reference Semantics.

image

Should we somehow emphasize such problems more somewhere?

Metadata

Metadata

Assignees

No one assigned

    Labels

    by-referenceIssues related to by-reference/copying behavior

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions