Question

Let's have:

DT1 <- data.table(iris)
DT2 <- DT1 # both reference the same memory location though
DT3 <- copy(DT1)

Question: Is there a way to check that DT2 keeps referencing the same memory location as DT1?

Something like this pseudo-function:

mem.identical(DT2, DT1) # should return TRUE
mem.identical(DT3, DT1) # should return FALSE

Unfortunately, identical or all.equal don't work for this purpose, because

identical(DT1,DT3) # gives TRUE

Only after introducing some change, the difference can be detected using identical:

DT1[,Test:=1] # introduces change to DT1 directly, to DT2 indirectly
identical(DT1,DT2) # TRUE - proves that DT2 is linked with DT1
identical(DT1,DT3) # FALSE - DT1 and DT3 are clearly decoupled
Was it helpful?

Solution

You can use data.table::address for this

> address(DT1)
[1] "0x10336c230"
> address(DT2)
[1] "0x10336c230"
> address(DT3)
[1] "0x10336cb50"

OTHER TIPS

Ok I found the answer on SO here, using tracemem:

DT1 <- data.table(iris)
DT2 <- DT1
DT3 <- copy(DT1)

identical(tracemem(DT1),tracemem(DT2)) # TRUE
identical(tracemem(DT1),tracemem(DT3)) # FALSE
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top