title: Converting R data.frame to matrix with levels of two factors as row and column names of the matrix
body: <p>I want to converting  <code>R</code> <code>data.frame</code> to <code>matrix</code> with levels of two factors as row and column names of the matrix. Here is a MWE. It is a lot of code to get the desired result and there might be more compact code for this purpose.</p>
  
  <pre><code>set.seed(12345)
  A &lt;- c("A1", "A2")
  B &lt;- c("B1", "B2", "B3")
  Y &lt;- runif(n=6, min=100, max=1000)
  df &lt;- data.frame(expand.grid(A=A, B=B), Y)
  df
  
  #    A  B        Y
  # 1 A1 B1 748.8135
  # 2 A2 B1 888.1959
  # 3 A1 B2 784.8841
  # 4 A2 B2 897.5121
  # 5 A1 B3 510.8329
  # 6 A2 B3 249.7346
  
  library(tidyr)
  df1 &lt;- spread(data = df, key = A, value = Y, fill = NA, convert = FALSE, drop = TRUE)
  df1
  
  #   B       A1       A2
  # 1 B1 748.8135 888.1959
  # 2 B2 784.8841 897.5121
  # 3 B3 510.8329 249.7346
  
  
  m1 &lt;- as.matrix(df1[,-1])
  rownames(m1) &lt;- df1[ ,1]
  m1
  
  #     A1       A2
  # B1 748.8135 888.1959
  # B2 784.8841 897.5121
  # B3 510.8329 249.7346
  </code></pre>