Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><code>x</code> is defined in the global environment, not in your function.</p> <p>If you try to modify a non-local object such as <code>x</code> in a function then R makes a copy of the object and modifies the copy so each time you run your anonymous function a copy of <code>x</code> is made and its ith component is set to 4. When the function exits the copy that was made disappears forever. The original <code>x</code> is not modified.</p> <p>If we were to write <code>x[i] &lt;&lt;- i</code> or if we were to write <code>x[i] &lt;- 4; assign("x", x, .GlobalEnv)</code> then R would write it back. Another way to write it back would be to set <code>e</code>, say, to the environment that <code>x</code> is stored in and do this:</p> <pre><code>e &lt;- environment() sapply(1:10, function(i) e$x[i] &lt;- 4) </code></pre> <p>or possibly this:</p> <pre><code>sapply(1:10, function(i, e) e$x[i] &lt;- 4, e = environment()) </code></pre> <p>Normally one does not write such code in R. Rather one produces the result as the output of the function like this:</p> <pre><code>x &lt;- sapply(1:10, function(i) 4) </code></pre> <p>(Actually in this case one could write <code>x[] &lt;- 4</code>.)</p> <p>ADDED:</p> <p>Using the <a href="http://r-proto.googlecode.com">proto package</a> one could do this where method <code>f</code> sets the ith component of the <code>x</code> property to 4.</p> <pre><code>library(proto) p &lt;- proto(x = 1:10, f = function(., i) .$x[i] &lt;- 4) for(i in seq_along(p$x)) p$f(i) p$x </code></pre> <p>ADDED:</p> <p>Added above another option in which we explicitly pass the environment that <code>x</code> is stored in.</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