Note that there are some explanatory texts on larger screens.

plurals
  1. POUnderstanding exactly when a data.table is a reference to (vs a copy of) another data.table
    text
    copied!<p>I'm having a little trouble understanding the pass-by-reference properties of <code>data.table</code>. Some operations seem to 'break' the reference, and I'd like to understand exactly what's happening.</p> <p>On creating a <code>data.table</code> from another <code>data.table</code> (via <code>&lt;-</code>, then updating the new table by <code>:=</code>, the original table is also altered. This is expected, as per:</p> <p><code>?data.table::copy</code> and <a href="https://stackoverflow.com/questions/8030452/pass-by-reference-the-operator-in-the-data-table-package">stackoverflow: pass-by-reference-the-operator-in-the-data-table-package</a></p> <p>Here's an example:</p> <pre><code>library(data.table) DT &lt;- data.table(a=c(1,2), b=c(11,12)) print(DT) # a b # [1,] 1 11 # [2,] 2 12 newDT &lt;- DT # reference, not copy newDT[1, a := 100] # modify new DT print(DT) # DT is modified too. # a b # [1,] 100 11 # [2,] 2 12 </code></pre> <p>However, if I insert a non-<code>:=</code> based modification between the <code>&lt;-</code> assignment and the <code>:=</code> lines above, <code>DT</code> is now no longer modified:</p> <pre><code>DT = data.table(a=c(1,2), b=c(11,12)) newDT &lt;- DT newDT$b[2] &lt;- 200 # new operation newDT[1, a := 100] print(DT) # a b # [1,] 1 11 # [2,] 2 12 </code></pre> <p>So it seems that the <code>newDT$b[2] &lt;- 200</code> line somehow 'breaks' the reference. I'd guess that this invokes a copy somehow, but I would like to understand fully how R is treating these operations, to ensure I don't introduce potential bugs in my code.</p> <p>I'd very much appreciate if someone could explain this to me.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload