Using `names(obj) <- names(dt)` could be problematic

Open
#5,079 4 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
3/5
Estimated time
1-2 days
Newbie friendliness
35/100
Issue type
Documentation
Clarity
Mostly clear
Activity status
Stale
Tech stack
r
Domain
documentation

Research direction

Start by reproducing the supplied R example, then read the data.table Do's and Don'ts wiki and the Reference Semantics vignette, which are the documentation locations mentioned. Done means documenting the names-vector aliasing behavior and guidance for avoiding the shown unexpected errors in an appropriate location.

Written by the indexing model from the issue text.

Description

by-reference

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?

Dominant language
R
Stars
3.9k
Forks
1.1k
Avg merge
14h 4m
Merged PRs (30d)
4

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from Rdatatable/data.table

All issues in Rdatatable/data.table

Similar issues

More R issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.