Skip to content

setDT and setkeyv inside function #5618

@ghost

Description

Hi all! This is likely related to #4783 and #4816.

Consider this example:

library(data.table)

x <- tibble::tibble(a = c(3,2,1))
foo <- function(dt) {
  print(address(dt))
  setDT(dt)
  print(address(dt))
  setkeyv(dt, "a")
  return(dt[])
}

> foo(x)
[1] "0x106cbd5c8"
[1] "0x115082a00"
   a
1: 1
2: 2
3: 3

The above is expected. From what I understood setDT will make a shallow copy of x and then reference another object, hence the change in address from 0x106cbd5c8 to 0x115082a00. However, what is unexpected to me is that the order of the original variable, x, also changed:

> x
   a
1: 1
2: 2
3: 3

Is this expected behavior? I thought that the setDT inside foo would make a shallow copy of the passed object, and would then reference that copy instead of the original, so that setkeyv would only arrange the data inside the function, but not the data outside the function. Just like in the example in this #SO where the data in the original variable is not modified.

Question: Why does setkeyv reorders x, even though we are calling setDT inside foo?

Metadata

Metadata

Assignees

No one assigned

    Labels

    by-referenceIssues related to by-reference/copying behavior

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions