title: R - How to extract values for the same named elements across multiple objects of the same type?
body: <p>I have a series of objects storing the results of some statistical models in my workspace. Call them "model1", "model2", etc. Each of these models has the same set of named elements attached, $coef, for example. I would like to extract into a list or vector the values stored in a particular element from all objects containing the string "model".</p>
  
  <p>The following code entered at the command line does what I want:</p>
  
  <pre><code>unlist(lapply(parse(text = paste0(ls()[grep("model", ls() )], "$", "coef")), eval))
  </code></pre>
  
  <p>From this, I've created the following generic function:</p>
  
  <pre><code>get.elements &lt;- function(object, element) {
      unlist(lapply(parse(text = paste0(ls()[grep(object, ls() )], "$", element)), eval))
  }
  </code></pre>
  
  <p>However, when I run this function I get the following error:</p>
  
  <pre><code>Error in parse(text = paste0(ls()[grep(object, ls() )], "$", element)) : 
    &lt;text&gt;:1:1: unexpected '$'
  1: $
     ^
  </code></pre>
  
  <p>Q1. Why does this code work when run from the command line but not as a function, and more importantly, how do I fix it?</p>
  
  <p>Q2. Even better, is there a simpler method that will accomplish the same thing? This seems like such a common task for statisticians and simulation modelers that I would expect some kind of command in the base package, yet I've been unable to find anything. Surely there must be a more elegant way to do this than my cumbersome method.</p>
  
  <p>Thanks for all help.</p>
  
  <p>--Dave</p>