title: R: How to set names in a nested list from attributes
body: <p>Edit: I rewrite this question, as I have two related questions that maybe could be answered better together...</p>
  
  <hr>
  
  <p>I've got some large nested <code>list</code>s with nearly the same structure and without names. All items of the <code>list</code> have <code>attr</code>ibutes and I want to assign these as names in all levels of the <code>list</code>. Furthermore I want to drop a needless list-level.</p>
  
  <p>So this:</p>
  
  <pre><code>before &lt;- list(list("value_1"), list(list("value_2a"), list("value_2b")), list(list("value_3a"), list("value_3b"), list("value_3c")), list("value_4"))
  for(i in 1:4) attr(before[[i]], "tag") &lt;- paste0("tag_", i)
  attr(before[[2]][[1]], "code") &lt;- "code_2a"
  attr(before[[2]][[2]], "code") &lt;- "code_2b"
  attr(before[[3]][[1]], "code") &lt;- "code_3a"
  attr(before[[3]][[2]], "code") &lt;- "code_3b"
  attr(before[[3]][[3]], "code") &lt;- "code_3c"
  str(before)
  ## List of 4
  ##  $ :List of 1
  ##   ..$ : chr "value_1"
  ##   ..- attr(*, "tag")= chr "tag_1"
  ##  $ :List of 2
  ##   ..$ :List of 1
  ##   .. ..$ : chr "value_2a"
  ##   .. ..- attr(*, "code")= chr "code_2a"
  ##   ..$ :List of 1
  ##   .. ..$ : chr "value_2b"
  ##   .. ..- attr(*, "code")= chr "code_2b"
  ##   ..- attr(*, "tag")= chr "tag_2"
  ##  $ :List of 3
  ##   ..$ :List of 1
  ##   .. ..$ : chr "value_3a"
  ##   .. ..- attr(*, "code")= chr "code_3a"
  ##   ..$ :List of 1
  ##   .. ..$ : chr "value_3b"
  ##   .. ..- attr(*, "code")= chr "code_3b"
  ##   ..$ :List of 1
  ##   .. ..$ : chr "value_3c"
  ##   .. ..- attr(*, "code")= chr "code_3c"
  ##   ..- attr(*, "tag")= chr "tag_3"
  ##  $ :List of 1
  ##   ..$ : chr "value_4"
  ##   ..- attr(*, "tag")= chr "tag_4"
  </code></pre>
  
  <p>(Note: 1st level list items have a "tag"-attribute, 2nd level items have a "code"-attribute.)</p>
  
  <p>Should be this:</p>
  
  <pre><code>after &lt;- list(tag_1="value_1", tag_2=list(code_2a="value_2a", code_2b="value_2b"), tag_3=list(code_3a="value_3a", code_3b="value_3b", code_3c="value_3c"), tag_4="value_4")
  str(after)
  ## List of 4
  ##  $ tag_1: chr "value_1"
  ##  $ tag_2:List of 2
  ##   ..$ code_2a: chr "value_2a"
  ##   ..$ code_2b: chr "value_2b"
  ##  $ tag_3:List of 3
  ##   ..$ code_3a: chr "value_3a"
  ##   ..$ code_3b: chr "value_3b"
  ##   ..$ code_3c: chr "value_3c"
  ##  $ tag_4: chr "value_4"
  </code></pre>
  
  <p>Since the lists are large, I want to avoid <code>for</code> loops, to get a better performance.</p>