title: Merge matrices from two lists in R
body: <p>Suppose I have two lists that include several matrices. The first list includes matrices with dimensions that differ from matrix to matrix:</p>
  
  <p>Code to create list1:</p>
  
  <pre><code>d&lt;-c(0,1,0,1)
  e&lt;-c(1,0,0,0)
  f&lt;-c(0,0,0,0)
  g&lt;-c(1,0,0,0)
  cn&lt;-c(1,2,3,4)
  p&lt;-data.frame(d,e,f,g)
  dimnames(p)&lt;-list(cn,cn)
  
  d&lt;-c(0,1,0,1,0)
  e&lt;-c(1,0,0,0,0)
  f&lt;-c(0,0,0,0,0)
  g&lt;-c(1,0,0,0,1)
  h&lt;-c(0,0,0,1,0)
  cn&lt;-c(1,2,3,4,5)
  q&lt;-data.frame(d,e,f,g,h)
  dimnames(q)&lt;-list(cn,cn)
  
  list1&lt;-list(p,q)
  names(list1)&lt;-1990:1991
  </code></pre>
  
  <p>List1:</p>
  
  <pre><code>list1
  
  $`1990`
    1 2 3 4
  1 0 1 0 1
  2 1 0 0 0
  3 0 0 0 0
  4 1 0 0 0
  
  $`1991`
    1 2 3 4 5
  1 0 1 0 1 0
  2 1 0 0 0 0
  3 0 0 0 0 0
  4 1 0 0 0 1
  5 0 0 0 1 0
  </code></pre>
  
  <p>The second list includes matrices that always have the same dimensions and include all cases that ever occur in the matrices of List1 (6,7 would occur in additional matrices in list1).</p>
  
  <p>Code to produce list2:</p>
  
  <pre><code>o&lt;-matrix(NA,nrow=7,ncol=7)
  dimnames(o)&lt;-list(1:7, 1:7)
  list2&lt;-list(o,o)
  names(list2)&lt;-1990:1991
  </code></pre>
  
  <p>List2:</p>
  
  <pre><code>list2
  $`1990`
     1  2  3  4  5  6  7
  1 NA NA NA NA NA NA NA
  2 NA NA NA NA NA NA NA
  3 NA NA NA NA NA NA NA
  4 NA NA NA NA NA NA NA
  5 NA NA NA NA NA NA NA
  6 NA NA NA NA NA NA NA
  7 NA NA NA NA NA NA NA
  
  $`1991`
     1  2  3  4  5  6  7
  1 NA NA NA NA NA NA NA
  2 NA NA NA NA NA NA NA
  3 NA NA NA NA NA NA NA
  4 NA NA NA NA NA NA NA
  5 NA NA NA NA NA NA NA
  6 NA NA NA NA NA NA NA
  7 NA NA NA NA NA NA NA
  </code></pre>
  
  <p>What I would like to do is to replace the NA's in list2 with, if available, the values from the respective matrix from list1, so that the result looks like this:</p>
  
  <pre><code>$`1990`
     1  2  3  4  5  6  7
  1  0  1  0  1 NA NA NA
  2  1  0  0  0 NA NA NA
  3  0  0  0  0 NA NA NA
  4  1  0  0  0 NA NA NA
  5 NA NA NA NA NA NA NA
  6 NA NA NA NA NA NA NA
  7 NA NA NA NA NA NA NA
  
  $`1991`
     1  2  3  4  5  6  7
  1  0  1  0  1  0  NA NA
  2  1  0  0  0  0  NA NA
  3  0  0  0  0  0  NA NA
  4  1  0  0  0  1  NA NA
  5  0  0  0  1  0  NA NA
  6  NA NA NA NA NA NA NA
  7  NA NA NA NA NA NA NA
  </code></pre>
  
  <p>I suppose there is a way to do this by using the merge command. However, I have not figured any solution out yet, so any input is highly welcome!</p>