title: Is there a way to self-identify a list element's name within purrr/lapply?
body: <p>I want to pull the name of a list element out as the text for a plot title within an <code>lapply()</code> or <code>map()</code> function. </p>
  
  <p>The point is to self-identify a list elements name within the lapply or map call, rather then supply them as an additional argument. My real use case already has other arguments going into the function, and I am curious if there is a way around doing that because it would simplify things quite a bit.</p>
  
  <p>Self Identify a list element within purrr::map or lapply
  Say I have a list</p>
  
  <pre><code>library(tidyverse)
  my_list &lt;- list(A = data.frame(level = factor(1:5),
                                 value = rnorm(5)),
                  B = data.frame(level = factor(1:5),
                                 value = rnorm(5)))
  </code></pre>
  
  <p>And a simple function to plot it</p>
  
  <pre><code>test_fun &lt;- function(named_list) {
    ggplot(named_list) +
      geom_col(aes(level, value)) +
      ggtitle(named_list)
  }
  </code></pre>
  
  <p>And I want to do something like this:</p>
  
  <pre><code>purrr::map(my_list, test_fun) 
  </code></pre>
  
  <p>...But have them titled "A" &amp; "B".</p>
  
  <p>The goal is to identify the name of elements "A" or "B" within map/lapply
  That way I can pass that name as the plot title without supplying them as another function argument.</p>
  
  <p>I've tried these within the function: </p>
  
  <pre><code>names(named_list)
  # &amp;
  attr(named_list, "name")
  </code></pre>
  
  <p>But they each will pull the names within element A or B, which is not the desired behavior. I want to be up one level.</p>
  
  <p>I know that I could pass the names as a separate object with map2</p>
  
  <pre><code>my_names &lt;- names(my_list)
  test_fun2 &lt;- function(named_list, my_names) {
    ggplot(named_list) +
      geom_col(aes(level, value)) +
      ggtitle(my_names)
  }
  </code></pre>
  
  <p>Then do this:</p>
  
  <pre><code>map2(my_list, my_names, test_fun2)
  </code></pre>
  
  <p>But is there a way to just insert the list element name instead of doing that? If there isn't that is fine, I am curious whether a way exists or if I'm stuck supplying the names.</p>
  
  <h1>EDIT: Looking for clarity on <code>imap()</code> answer:</h1>
  
  <p>I can get the <code>imap()</code> suggestions to work on my simple example but only with an anonymous function. If I could get some clarity on the below example I should be able to scale up to the more complicated use.</p>
  
  <h2>Why does this fail</h2>
  
  <pre><code>test_fun_imap &lt;- function(named_list) {
    ggplot(.x) +
      geom_col(aes(level, value)) +
      ggtitle(.y)
  }
  
  imap(my_list, test_fun_imap)
  </code></pre>
  
  <h2>But this works</h2>
  
  <pre><code>imap(my_list, ~{
    ggplot(.x) +
      geom_col(aes(level, value)) +
      ggtitle(.y)
  }
  )
  </code></pre>