Skip to content

setDT modifies the class of the origin data.frame #4784

Description

@OfekShilon

Take this code:

> d1 <- data.frame(a=c(1,2,3,4), b=c(2,3,4,5))
> d2 <- d1
> setDT(d2)  

At this point d2 is a shallow copy of d1, meaning they are not the same R object (although they point to the same columns).
d2's class is data.table, as expected, but so is d1

> class(d2)
[1] "data.table" "data.frame"
> class(d1)
[1] "data.table" "data.frame"

Unlike #4783 , I think this is an easy fix. In two places in setDT's source you see the pair of lines -

setattr(x, "class", .resetclass(x, "data.frame"))
setalloccol(x)

setalloccol is what initiates the shallow copy. If the order of the rows were reversed, the class of only the current shallow copy (d2 in the example above) would be modified, as expected.

# Output of sessionInfo()
R version 3.6.1 (2019-07-05)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19041)
Matrix products: default

Activity

  1. OfekShilon commented on Nov 15, 2020

    @OfekShilon
    ContributorAuthor

    The fix I proposed doesn't work well with magrittr pipes :(

    df<-data.frame(a=1)
    df %>% setDT
    class(df)  # data.frame
    

    So I can't offer a solution, but the problem remains.

  2. OfekShilon commented on Nov 19, 2020

    @OfekShilon
    ContributorAuthor

    It seems setDT never worked well with magrittr pipes...

    > d <- data.frame(a=1:2)
    > setDT(d)
    > truelength(d)
    [1] 1025
    > d <- data.frame(a=1:2)
    > d %>% setDT
    > truelength(d)
    [1] 0 
    
  3. added a commit that references this issue on Sep 5, 2024
    899e49b
  4. added this to the 1.17.0 milestone on Sep 5, 2024
  5. added a commit that references this issue on Oct 3, 2024
    b4538a0
  6. modified the milestones: 1.17.0, 1.18.0 on Jan 27, 2025
  7. modified the milestones: 1.18.0, 1.19.0 on Nov 17, 2025
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

    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