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?