title: Convert data frame from long to wide format with lots of columns in R
body: <p>This may have already been answered but I could not find exactly what I wanted.</p>
  <p>I have a data frame like:</p>
  <pre><code>Area &lt;- c(1,1,1,1,2,2,2,2,3,3,3,3)
  Scenario &lt;- c(a,b,c,d,a,b,c,d,a,b,c,d)
  Type &lt;- c(EV, EV, EV, EV, EV, EV, EV, EV, EV, EV, EV, EV,)
  Y2020 &lt;- c(0.5,0.6,0.7,0.8,0.9,1.0,1.1,1.2,1.3,1.4,1.5,1.6)
  Y2021 &lt;- c(0.2,0.4,0.5,0.6,0.8,1.0,1.0,1.1,1.2,1.5,1.3,1.5)
  y2022 &lt;- c(0.3,0.6,0.2,0.7,0.5,0.6,0.7,0.8,0.9,1.1,1.3,1.6)
  
  dt &lt;- data.frame(Area,Scenario, Y2020, Y2021, Y2022)
  </code></pre>
  <p>So will look something like:</p>
  <pre><code>Area  Scenario Type Y2020  Y2021  Y2022
   1       a      EV   0.5    0.2    0.3
   1       b      EV   0.6    0.4    0.6
   1       c      EV   0.7    0.5    0.8
   1       d      EV   0.8    0.6    0.7
   2       a      EV   0.9    0.8    0.5
   2       b      EV   1.0    1.0    0.6
   2       c      EV   1.1    1.0    0.7
   2       d      EV   1.2    1.1    0.8
   3       a      EV   1.3    1.2    0.9
   3       b      EV   1.4    1.5    1.1
   3       c      EV   1.5    1.3    1.3
   3       d      EV   1.6    1.5    1.6
  </code></pre>
  <p>I would like to get it in wide format by rotating by the Scenario column like this:</p>
  <pre><code>Area Type Y2020_a  Y2021_a  Y2022_a  Y2020_b  Y2021_b ...
   1    EV    0.5      0.2      0.3      0.6      0.4
   2    EV    0.9      0.8      0.5      1.0      1.0
   3    EV    1.3      1.2      0.9      1.4      1.5
  </code></pre>
  <p>I tried to use dcast(dt, id ~ Scenario, value.var=names(dt)[4:6]) as suggested by @Arun from <a href="https://stackoverflow.com/questions/27247078/reshape-multiple-values-at-once">Reshape multiple values at once</a> but it returned &quot;Error in .subset2(x, i, exact = exact) : recursive indexing failed at level 2&quot;</p>
  <p>This is a condensed version of my actual data so if it could be replicated with a larger data set that would be great!</p>
  <p>I hope someone can help! Thanks</p>