More weird behaviour with colnames and setcolorder

Open
#5,494 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
35/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Stale
Tech stack
r
Domain
data

Research direction

Start with the supplied R reprex and inspect the behavior of colnames() and setcolorder() in data.table. Trace how column names are exposed and reordered, then verify the result against the example so the vector values and names remain correctly associated after reordering.

Written by the indexing model from the issue text.

Description

by-reference

setcolorder messes with the names of a vector previously defined using colnames.
It appears that assigning names to a vector using colnames() is by reference, so reordering the columns of the table results in those vector names also being re-ordered, but the elements of the vector are not. This results in the vector elements no longer corresponding to the actual data columns of the table.

Is there a good reason that colnames should not provide a copy of the column names rather than a pointer?

library(data.table)
dt <- data.table(a=c(1,2,3), b=c('x','y','z'), c=as.POSIXct(Sys.time(), '2022-10-21 12:19:21'), d=as.integer(c(10,20,30)))
print(dt)
#>    a b                   c  d
#> 1: 1 x 2022-10-21 12:33:39 10
#> 2: 2 y 2022-10-21 12:33:39 20
#> 3: 3 z 2022-10-21 12:33:39 30
cl <- sapply(dt, function(x) class(x)[1])
names(cl) <- colnames(dt)
print(cl)
#>           a           b           c           d 
#>   "numeric" "character"   "POSIXct"   "integer"
str(cl)
#>  Named chr [1:4] "numeric" "character" "POSIXct" "integer"
#>  - attr(*, "names")= chr [1:4] "a" "b" "c" "d"

setcolorder(dt, c('b','c','d','a'))
print(cl)
#>           b           c           d           a 
#>   "numeric" "character"   "POSIXct"   "integer"
#The names of the vector cl have been re-order but the values not
#So now cl is completely erroneous even though it was not referenced in the setcolorder

Created on 2022-10-21 by the reprex package (v2.0.0)

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.