title: R List with sub-lists: Extract all elements that match a rule into array
body: <p>I have a R list of objects which are again lists of various types. I want "cost" value for all objects whose category is "internal". What's a good way of achieving this?</p>
  
  <p>If I had a data frame I'd have done something like </p>
  
  <pre><code>my_dataframe$cost[my_dataframe$category == "internal"]
  </code></pre>
  
  <p>What's the analogous idiom for a list?</p>
  
  <pre><code>mylist&lt;-list(list(category="internal",cost=2),
  list(category="bar",cost=3),list(category="internal",cost=4),
  list(category='foo',age=56))
  </code></pre>
  
  <p>Here I'd want to get c(2,4). Subsetting like this does not work: </p>
  
  <pre><code>mylist[mylist$category == "internal"]
  </code></pre>
  
  <p>I can do part of this by:</p>
  
  <pre><code>temp&lt;-sapply(mylist,FUN = function(x) x$category=="internal")
  mylist[temp]
  [[1]]
  [[1]]$category
  [1] "internal"
  
  [[1]]$cost
  [1] 2
  
  
  [[2]]
  [[2]]$category
  [1] "internal"
  
  [[2]]$cost
  [1] 4
  </code></pre>
  
  <p>But how do I get just the costs so that I can (say) sum them up etc.? I tried this but does not help much:</p>
  
  <pre><code>unlist(mylist[temp])
    category       cost   category       cost 
  "internal"        "2" "internal"        "4" 
  </code></pre>
  
  <p>Is there a neat, compact idiom for doing what I want? </p>