title: Obtain "key" from "value" in R
body: <p>I have created a list which itself consists of several lists.  I am trying to determine an efficient way to get the "key" from the "value".  I.e. if I specify ("cat" or "dog"), ("fish" or "chicken"), ("horse" or "donkey") how can I return "pet", "food", and "work" respectively.  I have tried to create a method with a for loop since I am not sure how else to approach with indexing by name.</p>
  
  <pre><code>pet &lt;- c("cat", "dog")
  food &lt;- c("fish", "chicken")
  work &lt;- c("horse", "donkey")
  
  types &lt;- c("pet", "food", "work")
  
  animal.list &lt;- vector(mode = "list", length = length(types))
  names(animal.list) &lt;- types
  
  for (i in types)
  {
    animal.list[[i]] &lt;-  vector(mode = "list", length = length(c("a", "b")))
    names(animal.list[[i]]) &lt;- c("a", "b")
    animal.list[[i]][["a"]] &lt;- eval(parse(text = i))[[1]]
    animal.list[[i]][["b"]] &lt;- eval(parse(text = i))[[2]]
  
  }
  </code></pre>
  
  <p>My attempt would look something like this, but hopefully I could use some kind of which( %in%) statement to do it more efficiently/compactly.</p>
  
  <pre><code>f &lt;- function(x)
  {
      ret &lt;- NULL
      for (i in animals)
      {
  
           if(x == animal.list[[i]][["a"]] | x == animal.list[[i]][["b"]])
           {
               ret &lt;- i
           }
       }
  
  }
  </code></pre>