<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/melt-and-cast-the-shape-of-your-data-frame-exercises/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://www.r-exercises.com/2018/06/22/melt-and-cast-the-shape-of-your-data-frame-exercises/"> R-exercises</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p><a rel="nofollow" href="https://i2.wp.com/www.r-exercises.com/wp-content/uploads/2018/06/melt.jpg?ssl=1" target="_blank"><img sizes="(max-width: 298px) 100vw, 298px" src="https://i0.wp.com/www.r-exercises.com/wp-content/uploads/2018/06/melt-298x300.jpg?resize=298%2C300&ssl=1" alt="" width="298" class="wp-image-11718" data-recalc-dims="1" height="300"></a></p>
<p> </p>
<p>Datasets often arrive to us in a form that is different from what we need for our modelling or visualisations functions who in turn don’t necessary require the same format.</p>
<p>Reshaping data.frames is a step that all analysts need but many struggle with. Practicing this meta-skill will in the long-run result in more time to focus on the actual analysis.</p>
<p>The solutions to this set will rely on data.table, mostly melt() and dcast() which are originally from the reshape2 package. However, you can also get practice out if it using your favourite base-R, tidyverse or any other method and then compare the results.</p>
<p>Solutions are available <a rel="nofollow" href="http://r-exercises.com/2018/06/22/11719/" target="_blank">here</a>.</p>
<p> </p>
<p><strong>Exercise 1</strong></p>
<p>Take the following data.frame <i>from</i> this form<br>
<code></code></p>
<pre>df &lt;- data.frame(id = 1:2, q1 = c(&quot;A&quot;, &quot;B&quot;), q2 = c(&quot;C&quot;, &quot;A&quot;), stringsAsFactors = FALSE)
df
  id q1 q2
1  1  A  C
2  2  B  A 
</pre>
<p><i>to</i> this<br>
<code></code></p>
<pre>  id question value
1  1       q1     A
2  2       q1     B
3  1       q2     C
4  2       q2     A
</pre>
<p> </p>
<p><strong>Exercise 2</strong></p>
<p>Do the opposite; return the data.frame back to it’s original form.</p>
<p><strong>Exercise 3</strong></p>
<p>Set up the data.frame in terms of questions. Such as the following:</p>
<p><code></code></p>
<pre>  question id_1 id_2
1       q1    A    B
2       q2    C    A

</pre>
<p> </p>
<p><strong>Exercise 4</strong></p>
<p>The data entry behind this data.frame went a little bit wrong. Get all the C and B entries into their corresponding columns<br>
<code></code></p>
<pre>df2 &lt;- data.frame(
  A = c(&quot;A1&quot;, &quot;A12&quot;, &quot;A31&quot;, &quot;A4&quot;), 
  B = c(&quot;B4&quot;, &quot;C7&quot;, &quot;C3&quot;, &quot;B9&quot;), 
  C = c(&quot;C3&quot;, &quot;B16&quot;, &quot;B3&quot;, &quot;C4&quot;)
)
</pre>
<p> </p>
<p><strong>Exercise 5</strong></p>
<p>Get this data.frame</p>
<p><code></code></p>
<pre>df3 &lt;- data.frame(
  Join_ID = rep(1:3, each = 2), 
  Type    = rep(c(&quot;a&quot;, &quot;b&quot;), 3), 
  v2      = c(8, 9, 7, 6, 5, 4)*10
)
</pre>
<p> </p>
<p>To look like this:</p>
<p><code></code></p>
<pre>  Join_ID a_v2 b_v2
1       1   80   90
2       2   70   60
3       3   50   40
</pre>
<p> </p>
<p><strong>Exercise 6</strong></p>
<p>Revisiting a dataset used in an earlier <a rel="nofollow" href="https://www.r-exercises.com/2017/08/23/basics-of-data-table-smooth-data-exploration/" target="_blank">exercise set on data exploration</a>;<br>
load the AER package and run the command <code>data(&quot;Fertility&quot;)</code> which loads the dataset Fertility to your workspace.<br>
Melt it into the following format, with one row per child.</p>
<p><code></code></p>
<pre>head(ferl)
  morekids age afam hispanic other work mother_id order gender
1       no  27   no       no    no    0         1     1   male
2       no  30   no       no    no   30         2     1 female
3       no  27   no       no    no    0         3     1   male
4       no  35  yes       no    no    0         4     1   male
5       no  30   no       no    no   22         5     1 female
6       no  26   no       no    no   40         6     1   male
</pre>
<p> </p>
<p><strong>Exercise 7</strong></p>
<p>Take this<br>
<code></code></p>
<pre>d1 = data.frame(
  ID=c(1,1,1,2,2,4,1,2), 
  medication=c(1,2,3,1,2,7,2,8)
)
d1
  ID medication
1  1          1
2  1          2
3  1          3
4  2          1
5  2          2
6  4          7
7  1          2
8  2          8
</pre>
<p>to this form:<br>
<code></code></p>
<pre>  
   ID medications
1:  1  1, 2, 3, 2
2:  2     1, 2, 8
3:  4           7
</pre>
<p> </p>
<p>Note the solution doesn’t use melt() nor dcast(), so you might look at other options.</p>
<p><strong>Exercise 8</strong></p>
<p>Get this<br>
<code></code></p>
<pre>dfs &lt;- data.frame(
  Name = c(rep(&quot;name1&quot;,3),rep(&quot;name2&quot;,2)),
  MedName = c(&quot;atenolol 25mg&quot;,&quot;aspirin 81mg&quot;,&quot;sildenafil 100mg&quot;, &quot;atenolol 50mg&quot;,&quot;enalapril 20mg&quot;)
)
dfs
   Name          MedName
1 name1    atenolol 25mg
2 name1     aspirin 81mg
3 name1 sildenafil 100mg
4 name2    atenolol 50mg
5 name2   enalapril 20mg
</pre>
<p> </p>
<p>Into the following format:<br>
<code></code></p>
<pre>    Name  medication_1   medication_2     medication_3
1: name1 atenolol 25mg   aspirin 81mg sildenafil 100mg
2: name2 atenolol 50mg enalapril 20mg             
</pre>
<p> </p>
<p><strong>Exercise 9</strong></p>
<p>Get the following data.frame organized in standard form<br>
<code></code></p>
<pre>df7 &lt;- data.table(
  v1 = c(&quot;name1, name2&quot;, &quot;name3&quot;, &quot;name4, name5&quot;),
  v2 = c(&quot;1, 2&quot;, &quot;3&quot;, &quot;4, 5&quot;), 
  v3 = c(1, 2, 3)
)
df7
             v1   v2 v3
1: name1, name2 1, 2  1
2:        name3    3  2
3: name4, name5 4, 5  3
</pre>
<p> </p>
<p>Expected output:</p>
<p><code></code></p>
<pre> 
      v1 v2 v3
1: name1  1  1
2: name2  2  1
3: name3  3  2
4: name4  4  3
5: name5  5  3
</pre>
<p> </p>
<p>The solution doesn’t use melt() nor dcast() and can be suprisingly hard.</p>
<p><strong>Exercise 10</strong></p>
<p>Convert this:<br>
<code></code></p>
<pre> 
df &lt;- data.frame(
 Method = c(&quot;10.fold.CV Lasso&quot;, &quot;10.fold.CV.1SE&quot;, &quot;BIC&quot;, &quot;Modified.BIC&quot;),
 n = c(30, 30, 50, 50, 50, 50, 100, 100),
 lambda = c(1, 3, 1, 2, 2, 0, 1, 2), 
df = c(21, 17, 29, 26, 25, 32, 34, 32) ) 
> df
            Method   n lambda df
1 10.fold.CV Lasso  30      1 21
2   10.fold.CV.1SE  30      3 17
3              BIC  50      1 29
4     Modified.BIC  50      2 26
5 10.fold.CV Lasso  50      2 25
6   10.fold.CV.1SE  50      0 32
7              BIC 100      1 34
8     Modified.BIC 100      2 32
</pre>
<p>Into<br>
<code></code></p>
<pre> 
            Method lambda_30 lambda_50 lambda_100 df_30 df_50 df_100
1 10.fold.CV Lasso         1         2               21    25       
2   10.fold.CV.1SE         3         0               17    32       
3              BIC                   1          1          29     34
4     Modified.BIC                   2          2          26     32  
</pre>
<p> </p>
<p>(Image by <a rel="nofollow" href="https://www.flickr.com/photos/joealterio/" target="_blank">Joe Alterio</a>)</p>
<div>
<h3>Related exercise sets:</h3>
<ol>
<li><a rel="nofollow" href="https://www.r-exercises.com/2017/11/29/spatial-data-analysis-introduction-to-raster-processing-part-1/" title="Spatial Data Analysis: Introduction to Raster Processing (Part 1)" target="_blank">Spatial Data Analysis: Introduction to Raster Processing (Part 1) </a></li>
<li><a rel="nofollow" href="https://www.r-exercises.com/2018/03/31/advanced-techniques-with-raster-data-part-3-regression-kriging/" title="Advanced Techniques With Raster Data – Part 3: Exercises" target="_blank">Advanced Techniques With Raster Data – Part 3: Exercises </a></li>
<li><a rel="nofollow" href="https://www.r-exercises.com/2018/02/28/advanced-techniques-with-raster-data-part-1-unsupervised-classification/" title="Advanced Techniques With Raster Data: Part 1 – Unsupervised Classification" target="_blank">Advanced Techniques With Raster Data: Part 1 – Unsupervised Classification </a></li>
<li><a rel="nofollow" href="http://www.r-exercises.com/start-here-to-learn-r/" target="_blank">Explore all our (>1000) R exercises</a></li>
<li><a rel="nofollow" href="http://www.r-exercises.com/r-courses/" target="_blank">Find an R course using our R Course Finder</a> directory</li>
</ol>
</div>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://www.r-exercises.com/2018/06/22/melt-and-cast-the-shape-of-your-data-frame-exercises/"> R-exercises</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/zCPu4c2D8Uk" height="1"></a></div>