<p><div><div><div><div data-width="100" data-show-faces="false" data-send="true" data-layout="button_count" data-height="21" data-href="https://www.r-bloggers.com/teaching-pivot-un-pivot/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://www.win-vector.com/blog/2017/04/teaching-pivot-un-pivot/"> R – Win-Vector Blog</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<h2>Authors: John Mount and Nina Zumel</h2>
<h2>Introduction</h2>
<p>In teaching thinking in terms of coordinatized data we find the hardest operations to teach are <a target="_blank" rel="nofollow" href="http://www.win-vector.com/blog/2017/04/visualizing-relational-joins/">joins</a> and <a target="_blank" rel="nofollow" href="http://www.win-vector.com/blog/2017/03/coordinatized-data-a-fluid-data-specification/">pivot</a>. </p>
<p>One thing we commented on is that <a target="_blank" rel="nofollow" href="https://cran.r-project.org/package=cdata">moving data values into columns</a>, or into a “thin” or entity/attribute/value form (often called “un-pivoting”, “stacking”, “<a target="_blank" rel="nofollow" href="https://www.jstatsoft.org/article/view/v059i10">melting</a>” or “<a target="_blank" rel="nofollow" href="http://r4ds.had.co.nz/tidy-data.html#spreading-and-gathering">gathering</a>“) is easy to explain, as the operation is a function that takes a single row and builds groups of new rows in an obvious manner. We commented that the inverse operation of moving data into rows, or the “widening” operation (often called “pivoting”, “unstacking”, “casting”, or “spreading”) is harder to explain as it takes a specific group of columns and maps them back to a single row. However, if we take extra care and factor the pivot operation into its essential operations we find pivoting can be usefully conceptualized as a simple single row to single row mapping followed by a grouped aggregation.</p>
<p>Please read on for our thoughts on teaching pivoting data.<span></span></p>
<p>
<h2>Background</h2>
<p>In data science data-rows are often considered to be instances. Because of this the data scientist needs explicit control over which facts fall into a single row. If we are trying to compute the relative prevalence of a birth-names by year broken down by sex we probably want both sexes in a single row. If we are trying to graph the same data using the <a target="_blank" rel="nofollow" href="https://cran.r-project.org/">R</a> package <a target="_blank" rel="nofollow" href="https://cran.r-project.org/package=ggplot2">ggplot2</a> we may want each year plus sex to determine a different row. Our <a target="_blank" rel="nofollow" href="http://www.win-vector.com/blog/2017/03/coordinatized-data-a-fluid-data-specification/">thesis</a> is that these differences are inessential for features of data presentation and not to be confused with properties of the underlying data.</p>
<p>Because we need to move from form to form we need both terminology to discuss the transforms and tools the implement the transforms.</p>
<p>For example when we were preparing <a target="_blank" rel="nofollow" href="https://github.com/WinVector/BigDataRStrata2017">our recent Strata workshop on Spark/R/Sparklyr</a> we started with <a target="_blank" rel="nofollow" href="https://github.com/rstudio/Strata2016">materials from our RStudio partners</a> and found ourselves puzzled by <a target="_blank" rel="nofollow" href="https://github.com/rstudio/Strata2016/blob/master/03b-Spark-SQL.Rmd">one bit of code</a>:</p>
<pre>
 birthsYearly &lt;- applicants_tbl %>%
  mutate(male = ifelse(sex == &quot;M&quot;, n_all, 0), 
         female = ifelse(sex == &quot;F&quot;, n_all, 0)) %>%
  group_by(year) %>%
  summarize(Male = sum(male) / 1000000, 
            Female = sum(female) / 1000000) %>%
  arrange(year) %>%
  collect
</pre>
<p>One of your authors (Nina Zumel) found this code much easier to understand once she added <a target="_blank" rel="nofollow" href="https://github.com/WinVector/BigDataRStrata2017/blob/master/Exercises/solutions/03b-Spark-SQL.md">a comment indicating intent</a> such as:</p>
<pre>
 # by-hand spread on remote data
</pre>
<p>And the other author (John Mount) noticed that this implementation of “pivot” or “spread” was a better implementation idea than he had previously been toying with to add “pivot” (or “move values to columns”) capabilities to remote data implementations (databases and Spark).</p>
<p>This two stage version of pivot (widening individual rows and then summarizing by groups) is also a great way to teach data shaping techniques, which we will discuss here.</p>
<h2>Teaching moving data to rows</h2>
<p>Moving data to rows is easy to teach through examples. Suppose we have the following data frame:</p>
<pre>
d &lt;- data.frame(
  index = c(1, 2, 3),
  meas1 = c('m1_1', 'm1_2', 'm1_3'),
  meas2 = c('m2_1', 'm2_2', 'm2_3'),
  stringsAsFactors = FALSE)
print(d)

#   index meas1 meas2
# 1     1  m1_1  m2_1
# 2     2  m1_2  m2_2
# 3     3  m1_3  m2_3
</pre>
<p>We can convert this into a “thin” form with a call such as the following:</p>
<pre>
library(&quot;dplyr&quot;)
library(&quot;cdata&quot;)
d2 &lt;- moveValuesToRows(d,
                       nameForNewKeyColumn= 'meastype',
                       nameForNewValueColumn= 'meas',
                       columnsToTakeFrom= c('meas1','meas2')) %>%
  arrange(index)
print(d2)

#   index meastype meas
# 1     1    meas1 m1_1
# 2     1    meas2 m2_1
# 3     2    meas1 m1_2
# 4     2    meas2 m2_2
# 5     3    meas1 m1_3
# 6     3    meas2 m2_3
</pre>
<p>The idea is: intent is documented through the method name and verbose argument bindings. As we mentioned in <a target="_blank" rel="nofollow" href="http://www.win-vector.com/blog/2017/03/coordinatized-data-a-fluid-data-specification/">our earlier article</a>, this transform is easy to teach as you can meaningfully think about it operating on each input row separately:</p>
<pre>
moveValuesToRows(d[1, , drop=FALSE],
                 nameForNewKeyColumn= 'meastype',
                 nameForNewValueColumn= 'meas',
                 columnsToTakeFrom= c('meas1','meas2')) %>%
  arrange(index)

#   index meastype meas
# 1     1    meas1 m1_1
# 2     1    meas2 m2_1
</pre>
<h2>Teaching moving data to columns</h2>
<p>As we taught <a target="_blank" rel="nofollow" href="http://www.win-vector.com/blog/2017/03/coordinatized-data-a-fluid-data-specification/">earlier</a>, with the proper pre-conditions, we can consider moving data to columns as an inverse operation to moving data to rows. We can undo the last transform with:</p>
<pre>
d1p &lt;- d2 %>%
  moveValuesToColumns(columnToTakeKeysFrom = 'meastype', 
                      columnToTakeValuesFrom = 'meas',
                      rowKeyColumns = 'index') %>%
  arrange(index)
all.equal(d, d1p)

 # [1] TRUE
</pre>
<p>Teaching moving data to columns at first blush seems harder as the operation as normally presented takes sets of rows as inputs. However, this is not an essential feature of moving data to columns. It is just an optimization or convenience that is so deeply ingrained into implementations it becomes part of the explanations.</p>
<p>Consider the following “incomplete” implementation of moving data to columns from the <a target="_blank" rel="nofollow" href="https://github.com/WinVector/replyr">development version of replyr</a>.</p>
<pre>
devtools::install_github(&quot;WinVector/replyr&quot;)
library(&quot;replyr&quot;)
d1q &lt;- d2 %>% 
  replyr_moveValuesToColumns(columnToTakeKeysFrom = 'meastype', 
                             columnToTakeValuesFrom = 'meas',
                             rowKeyColumns = 'index',
                             dosummarize = FALSE, 
                             fill = '') %>%
  arrange(index)
print(d1q)

#   index meas1 meas2
# 1     1  m1_1      
# 2     1        m2_1
# 3     2  m1_2      
# 4     2        m2_2
# 5     3  m1_3      
# 6     3        m2_3
</pre>
<p>This notation makes the motion of values to columns obvious: each row from the original data frame produces a single new row in the result data frame that:</p>
<ul>
<li>Has a new column for each possible values seen in “columnToTakeKeysFrom”.</li>
<li>Populates the column matching the value in “columnToTakeKeysFrom” with the value from “columnToTakeValuesFrom”.</li>
<li>Populates other new columns (those taking names from “columnToTakeKeysFrom”) with easy to remove placeholder values.</li>
<li>Copies over all other column values.</li>
</ul>
<p>Once we see this it becomes clear moving values to columns is an operation very much like the expansion of levels in “<code>stats::model.matrix()</code>” or 1-hot encoding (also called “dummy variables” or “indicators”), which place ones in columns instead of arbitrary values. </p>
<p><center><br>
<a target="_blank" rel="nofollow" href="http://www.practicaldatascience.com/"><img title="Indicators.png" alt="Indicators" src="https://i1.wp.com/www.win-vector.com/blog/wp-content/uploads/2017/04/Indicators.png?resize=390%2C197" border="0" data-recalc-dims="1"><br>
Dummy or indicator column encoding example from <em>Practical Data Science with R</em>, Zumel, Mount; Manning 2014.</a><br>
</center></p>
<p>In fact calling <code>model.matrix()</code> gives us a structure very similar to the “<code>d1q</code>” frame:</p>
<pre>
model.matrix(~ 0 + index + meastype, data = d2)

#   index meastypemeas1 meastypemeas2
# 1     1             1             0
# 2     1             0             1
# 3     2             1             0
# 4     2             0             1
# 5     3             1             0
# 6     3             0             1
</pre>
<p>The reason we bring this up is that things are easier to learn when they are in a shared, familiar context, and not treated as unique, “remarkable” occurrences.</p>
<p>To finish the conversion back to the original frame “<code>d</code>” we just have to add back in the neglected aggregation (which was intentionally suppressed by the “<code>dosummarize = FALSE</code>” option):</p>
<pre>
d1recovered &lt;- d1q %>%
  group_by(index) %>%
  summarize_all(&quot;max&quot;) %>%
  arrange(index)
print(d1recovered)

# # A tibble: 3 × 3
# index meas1 meas2
#   &lt;dbl> &lt;chr> &lt;chr>
# 1     1  m1_1  m2_1
# 2     2  m1_2  m2_2
# 3     3  m1_3  m2_3

all.equal(d, data.frame(d1recovered))

# [1] TRUE
</pre>
<p>And we have inverted the operation and recovered “<code>d</code>“! Demonstrating sequences of moving values to columns and moving values to rows is key to building familiarity and trust in these operations. This is whey we work such sequences here and in <a target="_blank" rel="nofollow" href="http://www.win-vector.com/blog/2017/03/coordinatized-data-a-fluid-data-specification/">our previous article</a> (yielding the following strongly connected graph converting between four different scientist’s preferred data representations):</p>
<p><center><br>
<a target="_blank" rel="nofollow" href="http://www.win-vector.com/blog/2017/03/coordinatized-data-a-fluid-data-specification/"><img src="https://i1.wp.com/www.win-vector.com/blog/wp-content/uploads/2017/03/directedGraph-1.png?w=246" data-recalc-dims="1"></a><br>
</center></p>
<h2>Conclusion</h2>
<p>The typical explanation of “pivot” for spreadsheet users contains aggregation as an integral part, and the typical explanations and diagrams used by <code>R</code> teachers also include a hidden aggregation (though only in the weaker sense of coalescing rows). Separating row transforms completely from value aggregation/coalescing makes pivoting (or moving values to columns) much more comprehendible and teachable.</p>
<p>We feel showing the notional intermediate form of the “expanded data frame” we introduced here when moving values to columns (the “<code>d1q</code>” frame) <em>greatly</em> improves learnability and comprehension. We also feel one should consistently use the terms “moving values to columns” and “moving values to rows” instead of insisting new students memorize non-informative technical name. Likely the “expanded data frame” is not taught as it is not usually the actual implementation (as it is in fact temporarily wasting space). </p>
<h2>Appendix</h2>
<p>The development version of <a target="_blank" rel="nofollow" href="https://github.com/WinVector/replyr"><code>replyr</code></a> now implements a move values to columns operation explicitly in terms of this expansion, and <a target="_blank" rel="nofollow" href="https://github.com/WinVector/BigDataRStrata2017/blob/master/Exercises/solutions/03b-Spark-SQL.md">we have demonstrated the method working on top of Spark2.0</a>. This “be temporarily wasteful” strategy is actually compatible with how one designs high-throughput big-data systems leaning hard on the aphorism: </p>
<blockquote><p>
“The biggest difference between time and space is that you can’t reuse time.”</p>
<p>Merrick Furst

</blockquote>
<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://www.win-vector.com/blog/2017/04/teaching-pivot-un-pivot/"> R – Win-Vector Blog</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 title="The R Project for Statistical Computing" rel="nofollow" href="https://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/search/data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="https://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/search/map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/search/animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/search/sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/search/SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/search/git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/search/hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/search/PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/search/time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/search/trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/CV9AjjTTAok"></a></div>