Note that there are some explanatory texts on larger screens.

plurals
  1. POR: Use function arguments as names for list sub elements
    text
    copied!<p>Here is a simplified example of what I am trying to do</p> <pre><code>set.seed(1) a &lt;- rnorm(10) b &lt;- rnorm(10) asdf&lt;-function(vec1,vec2){ mylist &lt;- list(sums = c(vec1 = sum(a), vec2 = sum(b)), products = c(vec1 = prod(a), vec2 = prod(b))) return(mylist) } asdf(a,b) </code></pre> <p>Here is the output:</p> <pre><code>$sums vec1 vec2 1.322028 2.488450 $products vec1 vec2 0.0026236813 0.0003054751 </code></pre> <p>The names of the list elements are based on the names I specified when defining the function, not the actual inputs used in the function. This makes sense, in general, but I would like to know how to change this behavior for a specific problem</p> <p>My desired output, given inputs <code>a</code> and <code>b</code> would be</p> <pre><code>$sums a b 1.322028 2.488450 $products a b 0.0026236813 0.0003054751 </code></pre> <p>Whatever the inputs are, be they <code>c(1,2,3,3,3,123)</code> and <code>c(2,1,1,5,7,1)</code> or <code>rnorm(10)</code> and <code>rpois(10)</code>, should be returned in the output.</p> <p>I know how to do the renaming after the function is done, but I want the naming to happen within the function. I've been looking at some other questions on SO, but haven't had anything work out quite right. </p> <p>A few things I've tried without success. </p> <pre><code>asdf&lt;-function(vec1,vec2){ name1&lt;- deparse(substitute(vec1)) name2&lt;- deparse(substitute(vec2)) mylist &lt;- list(sums = c(name1 = sum(a), name2 = sum(b)), products = c(name1 = prod(a), name2 = prod(b))) return(mylist) } asdf&lt;-function(vec1,vec2){ mylist &lt;- list(sums = c(name1 = sum(a), name2 = sum(b)), products = c(name1 = prod(a), name2 = prod(b))) assign(names(mylist(vec1,vec2)$sums, c(deparse(substitute(vec1)),deparse(substitute(vec2))))) return(mylist) } </code></pre> <p>It seems I may need to use <code>get</code> or <code>assign</code> or <code>match.call</code>, but I'm out of my league here. </p> <p>I feel a bit like a dunce reading some of these help pages. If I don't know enough to understand the help pages, well, I'm not nearly as good at R as I thought I was.</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