Note that there are some explanatory texts on larger screens.

plurals
  1. POSubtly different behaviour between with() and attach() in R?
    primarykey
    data
    text
    <p>People often use the <code>attach()</code> and <code>detach()</code> functions to set up "search paths" for variable names in R, but because this alters global state that's hard to keep track of, <a href="https://stackoverflow.com/questions/1310247/in-r-do-you-use-attach-or-call-variables-by-name-or-slicing/1311620#1311620">people</a> recommend <a href="https://stackoverflow.com/questions/5797797/attach-inside-function/5800785#5800785">using <code>with()</code> instead</a>, which sets up a temporary alteration to the search path for the duration of a single expression.</p> <p>However I just noticed that unlike <code>attach()</code>, <strong><code>with()</code> apparently doesn't "resolve through" functions</strong>. For example, let's first set up a dummy function that will access a variable named <code>x</code>:</p> <pre><code>f &lt;- function { print(x) } </code></pre> <p>Now,</p> <pre><code>with(list(x=42), f()) </code></pre> <p>fails even though</p> <pre><code>with(list(x=42), print(x)) </code></pre> <p>and</p> <pre><code>attach(list(x=42)) f() </code></pre> <p>both succeed! :(</p> <p>Can anyone tell me why? I would like <code>with()</code> to behave exactly like <code>attach()</code> does here, to enable me to effectively pass a big parameter list to a function by setting up an environment containing the parameter values with <code>with()</code>. I see this approach as having several benefits over the alternatives (the two I've considered are (a) laboriously passing all the parameters into the function, and (b) explicitly passing in a list/frame of parameters as a function argument and having the function itself call <code>with()</code>), but it doesn't work. I find this discrepancy pretty troubling to be honest! Any explanation/help would be appreciated.</p> <p>I'm using R 2.11.1.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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