title: a vector to an upper Triangle matrix by row in R
body: <p>I have a vector say</p>
  
  <pre><code>a = c(1,2,3,4,5,6) 
  </code></pre>
  
  <p>I would like to organize them into the elements into an upper triangle matrix (without considering diagonal elements, they are all zero) <strong>by row</strong>. My goal is to get the following matrix:</p>
  
  <pre><code>     [,1] [,2] [,3] [,4]
  [1,]    0    1    2    3
  [2,]    0    0    4    5
  [3,]    0    0    0    6
  [4,]    0    0    0    0
  </code></pre>
  
  <p>But the following way I do it is to replace the diagonal elements with this vector but assign values by column. For example,</p>
  
  <pre><code>b= matrix(0, 4, 4)
  b[upper.tri(b, diag=FALSE)]=a 
  </code></pre>
  
  <p>it will give me the following matrix</p>
  
  <pre><code>   [,1] [,2] [,3] [,4]
  [1,]    0    1    2    4
  [2,]    0    0    3    5
  [3,]    0    0    0    6
  [4,]    0    0    0    0
  </code></pre>
  
  <p>The reason is that when R assign values to a matrix, by default, it will assign them by column. I am wondering if there is a simple way to solve my problem without writing a for loop.</p>
  
  <p>I found a similar post before related to my problem but it does not explain assign values to a upper triangle matrix by row:</p>
  
  <p><a href="https://stackoverflow.com/questions/11786795/creating-a-triangular-matrix">creating a triangular matrix</a></p>
  
  <p>Thanks in advance!</p>