title: How to select an element of a list based on its name in a function?
body: <p>Consider this list:</p>
  
  <pre><code>l &lt;- list(a=1:10,b=1:10,c=rep(0,10),d=11:20)
  </code></pre>
  
  <p>Then consider this example code (representative of the real larger code). 
  It simply selects the right element in the list based on name.</p>
  
  <p>Parameters:</p>
  
  <p>object:a list with at maximum four elements (i.e, sometimes less than four). The elements are always called a,b,c and d but do not always appear in the same order in the list.</p>
  
  <p>x: name of element to select (i.e, a,b,c or d)</p>
  
  <pre><code>slct &lt;- function(object,x) {
     if (x=="a") {
      object$a
    } else if (x=="b") {
      object$b
    } else if (x=="c") {
      object$c
    } else if (x=="d") {
      object$d
    }
  }
  
  slct(l,"d")
  </code></pre>
  
  <p>That approach becomes impractible when you have not a mere 4 elements, but hundreds. 
  Moreover I cannot select based on a number (e.g., object[[1]]) because the elements don't come
  in the same order each time. So how can I make the above code shorter?</p>
  
  <p>I was thinking about the macro approach in SAS, but of course this doesn't work in R.</p>
  
  <pre><code>slct &lt;- function(object,x) {
  
    object$x
  }
  object$a
  
  slct(object=l,x="a")
  </code></pre>
  
  <p>What do I have to replace object$x with to make it work but with less code than in the above code?</p>