0

data.table setorder function also changes the ordering of another data.table.

library(data.table)
DT_setorder = data.table(name = c("aaaa", "bb", "ccc"), n_character = c(4,2,3))
DT_setorder_ORIGINAL = DT_setorder

#Sort DT_setorder by n_character in descending order
setorder(DT_setorder, -n_character)
DT_setorder
DT_setorder_ORIGINAL

# Here are results:
#> DT_setorder
# name n_character
# 1: aaaa 4
# 2: ccc 3
# 3: bb 2
# > DT_setorder_ORIGINAL
# name n_character
# 1: aaaa 4
# 2: ccc 3
# 3: bb 2

# Doing similar in dplyr
library(dplyr)
DT_FRAME = data.table(name = c("aaaa", "bb", "ccc"), n_character = c(4,2,3))
DT_FRAME_ORIGINAL <- DT_FRAME
# Sort DT_FRAME by n_character in descending order
DT_FRAME = DT_FRAME %>% arrange(n_character)
DT_FRAME
DT_FRAME_ORIGINAL

# Here are resuts
# > DT_FRAME
# name n_character
# 1: bb 2
# 2: ccc 3
# 3: aaaa 4
# > DT_FRAME_ORIGINAL
# name n_character
# 1: aaaa 4
# 2: bb 2
# 3: ccc 3

When I change an element of DT_setorder, the element of DT_setorder_ORIGINAL does not change. What should we pay attention to in order not to make mistakes while writing code? Should we always use the copy() command?

Does the situation I described above not happen when using data.frame? That is, when the data we assign with <- changes, does the assigned data also change?

user16217248
  • 3,119
  • 19
  • 19
  • 37
oguz
  • 1
  • 1
  • The `set*` functions in `data.table` work by _reference_, meaning that it does not make a copy of the dataset when things are adjusted. Its methods are fast and efficient, though this is very different from most other functions in R. You don't show it (and your question is poorly formatted, see https://stackoverflow.com/editing-help and https://meta.stackexchange.com/a/22189), but I'm inferring that you do `setorder(DT_setorder, n_character)`; before you did that, you made `DT_setorder_ORIGINAL` another symbol pointing to the same object in memory. If you want different, `copy(.)` it. – r2evans Jun 09 '23 at 12:59
  • I've marked this as a duplicate, since I feel the answers in that question do a much better job of explaining what I started saying in my previous comment. Please read the answers there (I know it's not short) and digest them, then feel free to come back and @-ping me if you have more questions. Good luck learning `data.table`! – r2evans Jun 09 '23 at 13:03

0 Answers0