title: Using assign to create objects in a for loop
body: <p>I have example data as follows:</p>
  <pre><code># Two lists of vectors
  
  A &lt;- list()
  B &lt;- list()
  
  patterns &lt;- c(&quot;A&quot;,&quot;B&quot;)
  
  A[[1]] &lt;- c(&quot;Aa&quot;, &quot;Aa&quot;, &quot;Ab&quot;, NA)
  names(A)[1] &lt;- &quot;A1&quot;
  
  A[[2]] &lt;- c(&quot;Aa&quot;, &quot;Aa&quot;, &quot;Ab&quot;, NA, NA)
  names(A)[2] &lt;- &quot;A2&quot;
  
  B[[1]] &lt;- c(&quot;Aa&quot;, &quot;Ab&quot;, NA, NA, &quot;Ab&quot;)
  names(B)[1] &lt;- &quot;B1&quot;
  
  B[[2]] &lt;- c(&quot;Aa&quot;, &quot;Ab&quot;, NA, &quot;Ab&quot;)
  names(B)[2] &lt;- &quot;B2&quot;
  </code></pre>
  <p>What I would like to do is to create data.frames from each list item, with only the unique values per list item.</p>
  <pre><code>for (j in 1:length(patterns)) {  
  
      # Keep unique values
      assign(paste0(&quot;Pattern_&quot;, patterns[[j]]), lapply(paste0(&quot;Pattern_&quot;, patterns[[j]]) ,function(x) unique(na.omit(x))))
  
      # Make lengths equal
      assign(paste0(&quot;Pattern_&quot;, patterns[[j]]), lapply(paste0(&quot;Pattern_&quot;, patterns[[j]]), `length&lt;-`, max(lengths(paste0(&quot;Pattern_&quot;, patterns[[j]])))))
  
      # Create data.frame
      assign(paste0(&quot;Pattern_&quot;, patterns[[j]]), data.frame(matrix(unlist(paste0(&quot;Pattern_&quot;, patterns[[j]])), nrow=length(paste0(&quot;Pattern_&quot;, patterns[[j]])), byrow=TRUE),stringsAsFactors=FALSE))
  }
  </code></pre>
  <p>I thought I did it right but somehow I get is:</p>
  <p><a href="https://i.stack.imgur.com/rh4lQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rh4lQ.png" alt="enter image description here" /></a></p>
  <p>What I want is:</p>
  <pre><code>A &lt;- lapply(A ,function(x) unique(na.omit(x)))
  A &lt;- lapply(A, `length&lt;-`, max(lengths(A)))
  # https://stackoverflow.com/questions/12639501/convert-list-to-data-frame-while-keeping-list-element-names
  A &lt;- data.frame(ID = rep(names(A), sapply(A, length)),
                   Match = unlist(A), row.names = NULL)
  
    ID Match
  1 A1    Aa
  2 A1    Ab
  3 A2    Aa
  4 A2    Ab
  </code></pre>
  <p>What am I doing wrong?</p>