Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing get inside lapply, inside a function
    primarykey
    data
    text
    <p>this may seem like a overly complicated question, but it has me driving me a little nuts for some time. It is also for curiosity, because I already have a way of doing what I need, so is not that important.</p> <p>In R, I need a function to return a named list object with all the arguments and the values entered by the user. For this I have made this code (toy example):</p> <pre><code>foo &lt;- function(a=1, b=5, h='coconut') { frm &lt;- formals(foo) parms &lt;- frm for (i in 1:length(frm)) parms[[i]] &lt;- get(names(frm)[i]) return(parms) } </code></pre> <p>So when this is asked:</p> <pre><code>&gt; foo(b=0) $a [1] 1 $b [1] 0 $h [1] "coconut" </code></pre> <p>This result is perfect. The thing is, when I try to use <code>lapply</code> to the same goal, so as to be a little more efficient (and elegant), it does not work as I want it to:</p> <pre><code>foo &lt;- function(a=1, b=5, h='coconut') { frm &lt;- formals(foo) parms &lt;- lapply(names(frm), get) names(parms) &lt;- names(frm) return(parms) } </code></pre> <p>The problem clearly is with the environment in which <code>get</code> evaluates it's first argument (a character string, the name of the variable). This I know in part from the error message:</p> <pre><code>&gt; foo(b=0) Error in FUN(c("a", "b", "h")[[1L]], ...) : object 'a' not found </code></pre> <p>and also, because when in the <code>.GlobalEnv</code> environment there are objects with the right names, foo returns their values instead:</p> <pre><code>&gt; a &lt;- 100 &gt; b &lt;- -1 &gt; h &lt;- 'wallnut' &gt; foo(b=0) $a [1] 100 $b [1] -1 $h [1] "wallnut" </code></pre> <p>Obviously, as <code>get</code> by default evaluates in the <code>parent.frame()</code>, it searches for the objects in the <code>.GlobalEnv</code> environment, instead of that of the current function. This is strange, since this does not happen with the first version of the function.</p> <p>I have tried many options to make the function <code>get</code> to evaluate in the right environment, but could not do it correctly (I've tried <code>pos=-2,0,1,2</code> and <code>envir=NULL</code> as options).</p> <p>If anyone happen to know a little more than me about environments, specially in this "strange" cases, I would love to know how to solve this.</p> <p>Thanks for your time,</p> <p>Juan</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