Skip to content

Instantly share code, notes, and snippets.

@jonocarroll
Created May 25, 2016 02:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonocarroll/a738212afde6394b4f251c7cac7f3348 to your computer and use it in GitHub Desktop.
Save jonocarroll/a738212afde6394b4f251c7cac7f3348 to your computer and use it in GitHub Desktop.
## load the data.table package
library(data.table)
## make this reproducible (up to memory locations)
set.seed(123)
## create a data.table with some dummy data
DT1 <- data.table(x=1:5, y=runif(5))
DT1
# x y
# 1: 1 0.2875775
# 2: 2 0.7883051
# 3: 3 0.4089769
# 4: 4 0.8830174
# 5: 5 0.9404673
## show the memory address of DT1
## NB: this will be different each time it is created
tracemem(DT1)
# [1] "<00000000175ACB80>"
## create a new name DT2 and point it to the memory address of DT1
## this is the default behaviour of `<-` for any object
DT2 <- DT1
## show the memory address of DT2
tracemem(DT2)
# [1] "<00000000175ACB80>"
## NB: the name DT2 points to the same memory address as DT1
## update row 2 column y of DT1 with an identifiable value
## note that data.table::set() operates in-memory and
## explicity does NOT copy objects unless it has to
## Note: this line has nothing to do with DT2
set(DT1, i=2L, j="y", value=999)
## now print out the two objects again. Notice anything?
DT1
# x y
# 1: 1 0.2875775
# 2: 2 999.0000000
# 3: 3 0.4089769
# 4: 4 0.8830174
# 5: 5 0.9404673
DT2
# x y
# 1: 1 0.2875775
# 2: 2 999.0000000
# 3: 3 0.4089769
# 4: 4 0.8830174
# 5: 5 0.9404673
## confirm that they still point to the same memory address
tracemem(DT1)
# [1] "<00000000175ACB80>"
tracemem(DT2)
# [1] "<00000000175ACB80>"
## if you want an explicitly copied value, use data.table::copy()
DT3 <- copy(DT1)
## confirm that they point to the different memory addresses
tracemem(DT1)
# [1] "<00000000175ACB80>"
tracemem(DT3)
# [1] "<00000000130BA598>"
## ########
## remember; names have objects (point to memory locations).
## ########
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment