<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/nrow-references-and-copies/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://statisfaction.wordpress.com/2017/12/10/nrow-references-and-copies/"> R – Statisfaction</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p> </p>
<div data-shortcode="caption" class="wp-caption"><img data-orig-file="https://statisfaction.files.wordpress.com/2017/12/b35a7afcb155bd9139d7ea13e61f97d6-monet-paintings-impressionist-paintings.jpg" data-orig-size="631,476" data-medium-file="https://statisfaction.files.wordpress.com/2017/12/b35a7afcb155bd9139d7ea13e61f97d6-monet-paintings-impressionist-paintings.jpg?w=400" data-attachment-id="6962" data-image-meta="{" data-image-description="" src="https://statisfaction.files.wordpress.com/2017/12/b35a7afcb155bd9139d7ea13e61f97d6-monet-paintings-impressionist-paintings.jpg?w=400&h=301&fit=450%2C600" data-permalink="https://statisfaction.wordpress.com/2017/12/10/nrow-references-and-copies/b35a7afcb155bd9139d7ea13e61f97d6-monet-paintings-impressionist-paintings/" data-large-file="https://statisfaction.files.wordpress.com/2017/12/b35a7afcb155bd9139d7ea13e61f97d6-monet-paintings-impressionist-paintings.jpg?w=631" alt="b35a7afcb155bd9139d7ea13e61f97d6--monet-paintings-impressionist-paintings" data-image-title="b35a7afcb155bd9139d7ea13e61f97d6–monet-paintings-impressionist-paintings" sizes="(max-width: 400px) 100vw, 400px" data-comments-opened="1" class="wp-image-6962" data-recalc-dims="1">
<p class="wp-caption-text">Claude Monnet’s paintings have nothing to do with the topic of this post.</p>
</div>
<p> </p>
<p>Hi all,</p>
<p>This post deals with a strange phenomenon in R that I have noticed while working on <a rel="nofollow" href="https://arxiv.org/abs/1708.03625" target="_blank">unbiased MCMC</a>. Reducing the problem to a simple form, consider the following code, which iteratively samples a vector ‘x’ and stores it in a row of a large matrix called ‘chain’ (I’ve kept the MCMC terminology).</p>
<pre>
dimstate = 100
nmcmc = 1e4
chain = matrix(0, nrow = nmcmc, ncol = dimstate)
for (imcmc in 1:nmcmc){
 if (imcmc == nrow(chain)){ #call to nrow
 }
 x = rnorm(dimstate, mean = 0, sd = 1)
 chain[imcmc,] = x #copying of x in chain
}
</pre>
<p>If you execute this code, you will see that it is surprisingly slow: it takes close to a minute on my computer. Now, consider the next block, which does exactly the same except that the vector ‘x’ is not copied into the matrix ‘chain’.</p>
<pre>
dimstate = 100
nmcmc = 1e4
chain = matrix(0, nrow = nmcmc, ncol = dimstate)
for (imcmc in 1:nmcmc){
if (imcmc == nrow(chain)){ #call to nrow
}
x = rnorm(dimstate, mean = 0, sd = 1)
# chain[imcmc,] = x #no more copying
}
</pre>
<p>This code runs nearly instantaneously. Could it be that just copying a vector in a matrix takes a lot of time? Sounds unlikely. Now consider this third block.</p>
<pre>
dimstate = 100
nmcmc = 1e4
chain = matrix(0, nrow = nmcmc, ncol = dimstate)
for (imcmc in 1:nmcmc){
if (imcmc == nmcmc){ #no call to nrow
}
x = rnorm(dimstate, mean = 0, sd = 1)
chain[imcmc,] = x #copying of x in chain
}
</pre>
<p>This code runs nearly instantaneously as well; this time ‘x’ is copied into ‘chain’, but the call to the nrow function is removed….?! What is nrow doing? It is meant to simply return dim(chain)[1], the first dimension of chain. So consider this fourth block.</p>
<pre>
dimstate = 100
nmcmc = 1e4
chain = matrix(0, nrow = nmcmc, ncol = dimstate)
for (imcmc in 1:nmcmc){
 if (imcmc == dim(chain)[1]){ #call to dim instead of nrow
 }
 x = rnorm(dimstate, mean = 0, sd = 1)
 chain[imcmc,] = x #copying of x in chain
}
</pre>
<p>This one also runs instantaneously! So replacing nrow(chain) by dim(chain)[1] solves the problem. Why?</p>
<p>The answer comes from R guru and terrific statistician <a rel="nofollow" href="http://www.louisaslett.com/" target="_blank">Louis Aslett</a>. I directly quote from an exchange of emails, since he brilliantly explains the phenomenon.</p>
<blockquote>
<p>You probably know R stores everything by reference, so if I do:</p>
<p>x &lt;-matrix(0, nrow=1e5, ncol=100)<br>
y &lt;-x</p>
<p>I actually only have one copy of the matrix in memory with two references to it. If I then do:</p>
<p>x[1,1] &lt;-1</p>
<p>R will first make a copy of the whole matrix, update x to point to that and then change the first element to one. This idea is used when you pass a variable to a standard (i.e. non-core, non-primitive) R function, which nrow is: it creates a reference to the variable you pass so that it doesn’t have to copy and the function call is very fast …. as long as you don’t write to it inside the function, no copy need ever happen. But the “bad design” bit is that R makes a decision whether to copy on write based only on a reference count and crucially that reference count stays increased even after a function returns, irrespective of whether or not the function has touched the variable.</p>
<p>So:</p>
<p>x &lt;-matrix(0, nrow=1e5, ncol=100) # matrix has ref count 1<br>
x[1,1] &lt;-1 # ref count is 1, so write with no copy<br>
nrow(x) # ref count is 2 even though nothing was touched<br>
x[1,1] &lt;-1 # ref count still 2, so R copies before writing first element. Now the ref count drops to 1 again<br>
x[2,2] &lt;-1 # this writes without a copy as ref count got reset on last line<br>
nrow(x) # ref count jumps<br>
x[3,3] &lt;-1 # copy invoked again! Aaaargh!</p>
<p>So by calling nrow in the loop for the first example, the chain matrix is being copied in full on every iteration. In the second example, chain is never written to so there is no negative side effect to the ref count having gone up. In the third example, chain only ever has ref count 1 so there are no copies and each row is written in-place. I did a quick bit of profiling and indeed in the slow example, the R garbage collector allocates and tidies up nearly 9GB of RAM when executing the loop!</p>
<p>The crazy thing is that dim(chain)[1] works full speed even though that is all that nrow is doing under the hood, but the reason is that dim is a so-called “primitive” core R function which is special because it doesn’t affect the reference counter of its arguments. If you want to dig into this yourself, there’s a function refs() in the pryr package which tells you the current reference count to any variable.</p>
</blockquote>
<p>Thanks Louis!</p>
<p> <a rel="nofollow" href="https://feeds.wordpress.com/1.0/gocomments/statisfaction.wordpress.com/6957/" target="_blank"><img border="0" alt="" src="https://feeds.wordpress.com/1.0/comments/statisfaction.wordpress.com/6957/"></a> <img border="0" alt="" src="https://i1.wp.com/pixel.wp.com/b.gif?resize=1%2C1&ssl=1" data-recalc-dims="1"></p>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://statisfaction.wordpress.com/2017/12/10/nrow-references-and-copies/"> R – Statisfaction</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/4n2SSuXNqtA" height="1"></a></div>