title: R: programmatic alternative for tidyr::spread?
body: <p>I have R data.frames that have varying amount of columns. The last column is numeric and the rest are character strings. I need to arrange them so that the last non-numeric column is spread. The difficulty is that I want to do this programmatically as I don't know the column names.</p>
  
  <p>E.g.</p>
  
  <pre><code>df &lt;- data.frame(varA = c("A1", "A1", "A2", "A2"),
                   varB = c("B1", "B2", "B1", "B2"),
                   val = c(1, 2, 3, 4))
  </code></pre>
  
  <p>I get where I want by</p>
  
  <pre><code>tidyr::spread(df, varB, val)
  </code></pre>
  
  <p>but I don't know how to achieve this when the name of the spread variable is not known. </p>
  
  <p>E.g. this won't work:</p>
  
  <pre><code>tidyr::spread(df, names(df)[ncol(df) - 1], val)
  </code></pre>
  
  <p>I've tried <code>tidyverse</code> solutions, but base R would be just as fine for me.</p>