title: How to create a vector from 2 merged matrices in R and fill in any dimension gaps with NA's?
body: <p>Suppose I have a 4x4 matrix generated as shown in the image below for <code>mat1</code>. (Image is from a snapshot of R Studio Console). Suppose I have another matrix generated of any size for example (1x2 in the below image for <code>mat2</code>). (In my code, the matrix elements and dimensions vary for both of the above matrices based on user inputs; though columns are only generated in multiples of 2, so I can have a [ ]x2 matrix, [ ]x4, [ ]x6, etc., and number of rows can be any integer).</p>
  <p>In my code these 2 matrices are merged into a vector (a vector is required for processing via R package <code>shinyMatrix</code>).</p>
  <p>Since these 2 matrix dimensions are variable, there are instances when merging the 2 matrices into a vector where you don't end up with the correct number of elements for converting back to a &quot;dimensionable&quot; matrix. As shown in the below image for <code>mat3</code>, where there are 18 elements after combining the 2 matrices <code>mat1</code> and <code>mat2</code> and certain elements must be dropped and NA's inserted to end up with a 4x4, 16 element matrix in this example.</p>
  <p>There are instances where <code>mat2</code> can have more elements than <code>mat1</code>. In this example I show <code>mat1</code> with 16 elements and <code>mat2</code> with 2 elements.</p>
  <p>Importantly, in the code only the first 2 columns of <code>mat1</code> can ever be replaced in this way with <code>mat2</code> values. Columns 3+ of <code>mat1</code> are never changed by <code>mat2</code>.</p>
  <p>Is there an efficient way to code this? Where you fit 2 matrices together into the dimensions of the larger matrix, and fill in any missing elements with NA?</p>
  <p>I'm going down the path of measuring the length of <code>mat1</code> columns 1 and 2, measuring the length of <code>mat2</code> columns 1 and 2, merging, replacing elements, etc., but with my limited experience it's looking very cumbersome and not working quite right. I bet R has a slick way to accomplish this sort of thing. One of the <code>apply</code> functions, like <code>mapply</code>? I read somewhere <code>mapply</code> is great for subsetting matrices.<code>Tibbles</code>?</p>
  <p>Here are my matrix inputs for the below image:</p>
  <pre><code>mat1 &lt;- matrix(c(1,2,NA,NA, 3,4,NA,NA, 5:12), ncol = 4)
  mat2 &lt;- matrix(c(10,30), ncol = 2)
  mat3 &lt;- c(mat2,mat1)
  </code></pre>
  <p><a href="https://i.stack.imgur.com/QVjFc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QVjFc.png" alt="enter image description here" /></a></p>