Redundant original column retained when using named vector in `cube()`'s `by` parameter

Open
#7,417 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

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

Research direction

Start by reproducing the named-vector case with cube() and compare it with [.data.table using the provided iris example. Trace how cube() handles by names and verify that the original column is absent while the renamed column remains, including the total row.

Written by the indexing model from the issue text.

Description

When using a named vector in the by parameter of cube(), the output incorrectly retains the original unrenamed column (with NA values) alongside the intended renamed column. This differs from the behavior of [.data.table's by parameter, which properly uses the vector names to rename grouped columns without retaining originals.

library(data.table)

dt_iris <- as.data.table(iris)

# Expected behavior in [.data.table: renamed column only, no original
dt_iris[, .N, by = c(S = "Species")]
#>             S     N
#>        <fctr> <int>
#> 1:     setosa    50
#> 2: versicolor    50
#> 3:  virginica    50

# Unexpected behavior in cube(): original "Species" column retained with NA
cube(dt_iris, .N, by = c(S = "Species"))
#>    Species     N          S
#>     <fctr> <int>     <fctr>
#> 1:    <NA>    50     setosa
#> 2:    <NA>    50 versicolor
#> 3:    <NA>    50  virginica
#> 4:    <NA>   150       <NA>

Created on 2025-11-06 with reprex v2.1.1

# Output of sessionInfo()

R version 4.4.1 (2024-06-14)
Platform: aarch64-apple-darwin20
Running under: macOS 26.0.1

Matrix products: default
BLAS:   /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib 
LAPACK: /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/lib/libRlapack.dylib;  LAPACK version 3.12.0

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

time zone: Asia/Shanghai
tzcode source: internal

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

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

loaded via a namespace (and not attached):
[1] compiler_4.4.1    tools_4.4.1       rstudioapi_0.16.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.