Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if two `data.table`s point to the same memory location [duplicate]

Tags:

r

data.table

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
like image 390
Daniel Krizian Avatar asked May 10 '14 18:05

Daniel Krizian


2 Answers

You can use data.table::address for this

> address(DT1)
[1] "0x10336c230"
> address(DT2)
[1] "0x10336c230"
> address(DT3)
[1] "0x10336cb50"
like image 133
GSee Avatar answered Oct 20 '22 00:10

GSee


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
like image 42
Daniel Krizian Avatar answered Oct 20 '22 01:10

Daniel Krizian