<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/showing-some-respect-for-data-munging/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://methodmatters.blogspot.com/2017/08/showing-some-respect-for-data-munging.html"> Method Matters</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>In this post, I’d like to focus on data munging, e.g. the process of acquiring and arranging data (typically in a <a rel="nofollow" href="http://vita.had.co.nz/papers/tidy-data.html" target="_blank">tidy</a> manner) prior to data analysis. It’s common knowledge that data scientists spend an enormous amount of time munging data, but data analysis, modeling, and visualization get most of the attention at presentations, on blogs and in the popular imagination. In my current role as a “data scientist,” I spend far more time doing data munging than I do modeling. So let’s show some respect for this process by dedicating a post to it!</p>
<p>The data come from a website on which consumers can rate their perceptions of different products in the consumer beverage category. Consumers select a specific beverage, give it an overall rating, and can indicate their perceptions of the drink (specifically, the presence or absence of different characteristics).</p>
<p>Our end goal, which I will discuss in my next post, is to use the ratings to perform a product segmentation, which will give us insight into how consumers perceive products within the beverage category. In order to reach that goal, we have to distill the information about the different beverages and the information from the consumer reviews into a single matrix that will allow us to derive these answers (with the right type of analysis).</p>
<p>As the past couple of posts focused on data analysis using Python, in this exercise I’ll switch back to R. </p>
<div><b>The Data</b></div>
<p>As is often the case, the data we need do not exist in a single tidy dataset. There are two different tables that contain different pieces of information about the beverages and the consumer evaluations.</p>
<p><i>The Review Data </i></p>
<p>The first dataset contains basic information on the reviews. These data contain one line per consumer review, and have a column describing the review id number, the drink name, the drink category (there are three different categories of beverages in these data), and the overall rating score. Here’s a sample of what the data look like:</p>
<div><a rel="nofollow" href="https://i2.wp.com/4.bp.blogspot.com/-GiauN47Wc9U/WQWQS2SIe3I/AAAAAAAAASc/ZZLrTE5kQloM-NQxRNHnaUgzj14zBydwwCLcB/s1600/Reviews_Raw.PNG?ssl=1" target="_blank"><img border="0" src="https://i2.wp.com/4.bp.blogspot.com/-GiauN47Wc9U/WQWQS2SIe3I/AAAAAAAAASc/ZZLrTE5kQloM-NQxRNHnaUgzj14zBydwwCLcB/s1600/Reviews_Raw.PNG?w=456&ssl=1" data-recalc-dims="1"></a></div>
<p><i>The Perceptions Data </i></p>
<p>The second dataset contains information on the consumer perceptions. Consumers can indicate their perceptions of each drink on a number of different dimensions. In this post, I’ll focus on the <b>feelings </b>induced by each beverage, characterized by <i>sensations </i>such as “happy” and “energetic.” The dataset contains one line per perception, and has columns indicating the perception “Group” (here we’re focusing on <b>feelings</b>, but other perceptions such as flavor are also present in the data), and the specific <i>sensation </i>within the feeling group (e.g. happy, energetic, etc.). This dataset can contain multiple lines per consumer review, if consumers indicated the presence of multiple characteristics for a given beverage. The id number in the perceptions data corresponds to the id number in the review data (though, as is often the case with real-world data, they do not share the same variable name). The head of the second dataset looks like this:</p>
<div><a rel="nofollow" href="https://i2.wp.com/1.bp.blogspot.com/-KIrC6YO-ywM/WQbfBlTwzdI/AAAAAAAAAUg/KkFfaJM1Nm0kPFEmjAqNZlWbkHsvU4IdwCLcB/s1600/Perceptions_Raw.PNG?ssl=1" target="_blank"><img border="0" src="https://i2.wp.com/1.bp.blogspot.com/-KIrC6YO-ywM/WQbfBlTwzdI/AAAAAAAAAUg/KkFfaJM1Nm0kPFEmjAqNZlWbkHsvU4IdwCLcB/s1600/Perceptions_Raw.PNG?w=456&ssl=1" data-recalc-dims="1"></a></div>
<p>
<div></div>
<div><b>Step 1: Aggregate the Perceptions Data to the Review Level</b></div>
<p>We first need to aggregate the perceptions data to the review level, in order to merge them in with the review dataset.</p>
<p>We have a number of different “Groups” of perceptions (e.g. feeling, flavor, etc.), and within each different group, we can have different sensations (e.g. happy, energetic, etc.). We can therefore see the combination of group and sensation to be the sensible unit of aggregation; the combination of both variables provides the best descriptor of the information provided by the consumers.</p>
<p>The perceptions dataset is called “perceptions_reviewid”. We can simply concatenate the group and sensation columns using base R:</p>
<pre><span># combine group and sensation into one variable called &quot;grp_sens&quot;</span><br><span>perceptions_reviewid</span><span>$</span><span>grp_sens</span> <span>&lt;-</span> paste0(<span>perceptions_reviewid</span><span>$</span><span>Group</span>, <span>&quot;_&quot;</span>, <br><span>perceptions_reviewid</span><span>$</span><span>Sensation</span>)<br><br></pre>
<p>The head of our dataset now looks like this:</p>
<div><a rel="nofollow" href="https://i2.wp.com/3.bp.blogspot.com/-W86yWS2A4cY/WQbfYxHzHEI/AAAAAAAAAUk/DpMc12lCilskEqCtFyI99Om5qzYrb-twQCLcB/s1600/Perceptions_Concat.PNG?ssl=1" target="_blank"><img border="0" src="https://i2.wp.com/3.bp.blogspot.com/-W86yWS2A4cY/WQbfYxHzHEI/AAAAAAAAAUk/DpMc12lCilskEqCtFyI99Om5qzYrb-twQCLcB/s1600/Perceptions_Concat.PNG?w=456&ssl=1" data-recalc-dims="1"></a></div>
<p>
<div></div>
<p>In aggregating this information to the review level, we are faced with two basic issues: 1) transforming the data from the <a rel="nofollow" href="https://en.wikipedia.org/wiki/Wide_and_narrow_data" target="_blank">“long” to the “wide” format</a> and 2) representing the information contained in the combination of group and sensation (the “grp_sens” variable) in a numeric format.</p>
<p>The “long” to the “wide” format conversion expresses our desire to aggregate the data to the level of the review, in order to merge it in with our review dataset. We currently have multiple rows per id (a “long” format); we want to end up with a single row per id with the different levels of “grp_sens” (representing the group and sensation information) each contained in one column (a “wide” format).</p>
<p>The representation of the data in numeric format is critical for further aggregation and analysis. Currently, we have the presence or absence of a given perception indicated with text; in our aggregated dataset we would like the presence of a given sensation (one sensation per column) indicated as a 1, and its absence as a 0.</p>
<p>I used the <b>tidyr </b>and <b>dplyr </b>packages, along with this <a rel="nofollow" href="http://stackoverflow.com/questions/25811756/summarizing-counts-of-a-factor-with-dplyr" target="_blank">super-helpful StackOverflow response</a>, in order to achieve this.</p>
<pre>library(<span>plyr</span>); library(<span>dplyr</span>)<br>library(<span>tidyr</span>)<br><br><span># long-to-wide transformation with numeric indicators</span><br><span># for presence/absence of each group/sensation combination</span><br><span># at the review level</span><br><span>perceptions_review_level</span> <span>&lt;-</span> <span>perceptions_reviewid</span> %<span>></span>% <br>                          group_by(<span>id_perceptions</span>, <span>grp_sens</span>)  %<span>></span>% <br>                          summarize(<span>n</span> <span>=</span> n()) %<span>></span>%   ungroup() %<span>></span>%<br>                          spread(<span>grp_sens</span>, <span>n</span>, <span>fill</span>=<span>0</span>)<br><br></pre>
<p>Essentially, we first group the data by <i>id </i>and <i>grp_sens</i> and count the frequency of each combination (as each person can only choose each combination once, the only value this can take will be 1). We then ungroup the data and spread out the <i>grp_sens</i> variable into the columns, filling each column with the number of observations per review (which, as we note above, will only take the value of 1). We then fill missing values (which occur when a given level of <i>grp_sens</i> <u>did not</u> occur in a review) with 0. Voilà!</p>
<p>
<div><a rel="nofollow" href="https://i0.wp.com/3.bp.blogspot.com/-NZ7UOz8GVxY/WQbf-D-uw7I/AAAAAAAAAUs/MdeeC_4ZRn4L91HF6L7j6ByS6wWsJiNaQCLcB/s1600/Perceptions_Review_Level.PNG?ssl=1" target="_blank"><img border="0" src="https://i0.wp.com/3.bp.blogspot.com/-NZ7UOz8GVxY/WQbf-D-uw7I/AAAAAAAAAUs/MdeeC_4ZRn4L91HF6L7j6ByS6wWsJiNaQCLcB/s1600/Perceptions_Review_Level.PNG?w=456&ssl=1" data-recalc-dims="1"></a></div>
<div></div>
<div><b>Step 2: Merge the Review Data and Aggregated Perceptions Data </b></div>
<p>Now we need to merge the two review-level datasets. Our review dataset is simply called “reviews” and our wide-format perceptions dataset is called “perceptions_review_level.”</p>
<p>Before merging datasets, I always like to do some basic descriptive statistics on the key variables used in the merge. This type of checking can save lots of trouble down the road in the analysis pipeline, and is one of the “insider” tips and tricks that isn’t mentioned enough when discussing data munging.</p>
<p>We will be merging on the id variable which is present in both datasets (albeit with a different name in each dataset). Let’s see how many id’s overlap with each other, and ensure that there are no duplicate id’s in either dataset. (Duplicate id’s will mess up many merges/joins, causing a dataset to increase dramatically in length, depending on the extent of the duplication). </p>
<pre><span># number of perceptions id's that correspond to an id in the review data </span><br>sum(<span>reviews</span><span>$</span><span>id_reviews</span> <span>%in%</span> <span>perceptions_review_level</span><span>$</span><span>id_perceptions</span>)<br><span># 105324</span><br><br><span># number of review id's that correspond to an id in the perception data </span><br>sum(<span>perceptions_review_level</span><span>$</span><span>id_perceptions</span> <span>%in%</span> <span>reviews</span><span>$</span><span>id_reviews</span>  )<br><span># 105324</span><br><br><span># are there duplicate ids for the review data?</span><br>sum(duplicated(<span>reviews</span><span>$</span><span>id_reviews</span>))<br><span># 0</span><br><br><span># are there duplicate ids for the perceptions data?</span><br>sum(duplicated(<span>perceptions_review_level</span><span>$</span><span>id_perceptions</span>))<br><span># 0</span><br><br></pre>
<p>We have the same number of matching id’s in both datasets: 105,324, and no duplicate id’s in either dataset, which means that we can proceed with our merge.</p>
<p>We will use dplyr to merge the datasets, specifying the id variables as the “key” in the merge. We’ll use an <a rel="nofollow" href="https://en.wikipedia.org/wiki/Join_(SQL)#Inner_join" target="_blank">inner join</a>, because we can only analyze beverages with information from both sources. We will immediately check to see whether our merged dataset has the correct number of rows (105,324, the number of matching id’s in both datasets).</p>
<pre><span># merge the review and perception data</span><br><br><span># inner join because we only want those with values in both datasets</span><br><span># it does us no good to have information in only one </span><br><span># (e.g. drink name but no perceptions, perceptions but no drink name)</span><br><span>review_level_omnibus</span> <span>&lt;-</span> dplyr<span>:</span><span>:</span>inner_join(<span>reviews</span>, <span>perceptions_review_level</span>,  <br>                                    <span>by</span> <span>=</span> c(<span>&quot;id_reviews&quot;</span> <span>=</span> <span>&quot;id_perceptions&quot;</span>))<br><br><span># check the dimensions: rows should be equal to </span><br><span># the number of matching id's above</span><br>nrow(<span>review_level_omnibus</span>)<br><span># 105324</span><br><br></pre>
<p>As expected, our merged dataset (called “review_level_omnibus”) has 105,324 rows, the same as the number of matching id’s between the two datasets. The head of our merged dataset looks like this:</p>
<div><a rel="nofollow" href="https://i1.wp.com/2.bp.blogspot.com/-e-0lysD-Yo4/WQbgtFVNgpI/AAAAAAAAAU0/cC4PgVR7ha8VCiWonBh3l8Gjlo72U2yXQCLcB/s1600/Review_Level_Omnibus.PNG?ssl=1" target="_blank"><img border="0" src="https://i1.wp.com/2.bp.blogspot.com/-e-0lysD-Yo4/WQbgtFVNgpI/AAAAAAAAAU0/cC4PgVR7ha8VCiWonBh3l8Gjlo72U2yXQCLcB/s1600/Review_Level_Omnibus.PNG?w=456&ssl=1" data-recalc-dims="1"></a></div>
<div></div>
<p> <b> </b>
<div><b>Step 3: Aggregate the Merged Data to the Beverage Level </b></div>
<p>We now have 1 row per review, with differing numbers of reviews per beverage. This is simply due to how the data were generated- consumers (website visitors) could leave reviews of whatever beverages they wanted to, and so our sample is inherently unbalanced in this regard. While many techniques are available for investigating consumer preferences with perfectly balanced samples (e.g. where every member of a consumer panel evaluates every beverage on every perceptive dimension), we will have to aggregate our data to the beverage level for our analysis. This will allow us to understand consumer perceptions of the beverage category across all raters, but it ignores potential variation in perceptions between individual consumers.</p>
<p>There are two different aggregations I would like to do on these data. The first concerns the numeric consumer evaluations. For each drink, we will take the average of the rating variable, as well as the average of the 0/1 perception variables. Because the perceptions data are coded with zeroes and ones, when we take the average of these variables, we are simply calculating the percentage of the reviews per beverage that contained a given perception (e.g. the percentage of  reviews for a given beverage that indicated “happy” feelings).</p>
<pre><span># get the mean values per beverage: rating and perceptions </span><br><span>drink_level_perceptions</span> <span>&lt;-</span> <span>review_level_omnibus</span> %<span>></span>% <br>                group_by(<span>Name</span>) %<span>></span>% summarise_each_(funs(<span>mean</span>), <br>                names(<span>review_level_omnibus</span>[,c(<span>4</span><span>:</span>ncol(<span>review_level_omnibus</span>))]) )<br><br></pre>
<p>This aggregation yields a dataset whose head looks like this:</p>
<div><a rel="nofollow" href="https://i2.wp.com/2.bp.blogspot.com/-AhbAwFjBa04/WQbi9JKevzI/AAAAAAAAAVA/P-QIQtRGGjYnwEqpuZUXhFBJYawVO0A2ACLcB/s1600/Drink_Level_Perceptions.PNG?ssl=1" target="_blank"><img border="0" src="https://i2.wp.com/2.bp.blogspot.com/-AhbAwFjBa04/WQbi9JKevzI/AAAAAAAAAVA/P-QIQtRGGjYnwEqpuZUXhFBJYawVO0A2ACLcB/s1600/Drink_Level_Perceptions.PNG?w=456&ssl=1" data-recalc-dims="1"></a></div>
<div></div>
<p>The second aggregation concerns the Category (there are 3 different beverage categories in our data) and the number of reviews for each beverage. Category is constant across each beverage (e.g. each beverage only has one category), while the number of reviews can vary across beverages. We aggregate the data to the beverage level using dplyr:</p>
<pre><span># get the category and number of reviews per beverage </span><br><span>drink_level_rest</span> <span>&lt;-</span> <span>review_level_omnibus</span> %<span>></span>% <br>  group_by(<span>Name</span>) %<span>></span>%  summarize(<span>Category</span> <span>=</span> <span>Category</span>[<span>1</span>],<br>                                <span>Num_Obs</span> <span>=</span> n())<br><br></pre>
<p>Which yields a dataset whose head looks like this:</p>
<div><a rel="nofollow" href="https://i2.wp.com/2.bp.blogspot.com/-LL02iFt9sQA/WQXtcth6CgI/AAAAAAAAAUE/2yNyjeVTG9YLNuxW-RsTc7cHTCjGCUMHACLcB/s1600/Drink_Level_Rest.PNG?ssl=1" target="_blank"><img border="0" src="https://i2.wp.com/2.bp.blogspot.com/-LL02iFt9sQA/WQXtcth6CgI/AAAAAAAAAUE/2yNyjeVTG9YLNuxW-RsTc7cHTCjGCUMHACLcB/s1600/Drink_Level_Rest.PNG?w=456&ssl=1" data-recalc-dims="1"></a></div>
<p><i>(Note- I didn’t think it was possible to combine these two different aggregations in a single dplyr chain. If I’m wrong, please let me know in the comments!)</i></p>
<div><b>Step 4: Merge the Beverage-Level Dataset </b></div>
<p>We will now merge these two aggregated datasets together on the beverage name (“Name”). (I’ve done the type of checks I describe above on the merging variable, but am not showing them here for the sake of brevity).</p>
<pre><span># merge drink-level datasets together</span><br><span>drink_level_omnibus</span> <span>&lt;-</span> dplyr<span>:</span><span>:</span>left_join(<span>drink_level_rest</span>, <br>                              <span>drink_level_perceptions</span>, <span>by</span> <span>=</span> <span>&quot;Name&quot;</span>)<br><br></pre>
<p>The head of our final merged beverage-level dataset looks like this:</p>
<div><a rel="nofollow" href="https://i1.wp.com/2.bp.blogspot.com/-IJOHade7OUY/WQbjdObBIEI/AAAAAAAAAVI/BbVBPaCuRC4OlgxpXJs15RYcba1tOE4xACLcB/s1600/Drink_Level_Omnibus.PNG?ssl=1" target="_blank"><img border="0" src="https://i1.wp.com/2.bp.blogspot.com/-IJOHade7OUY/WQbjdObBIEI/AAAAAAAAAVI/BbVBPaCuRC4OlgxpXJs15RYcba1tOE4xACLcB/s1600/Drink_Level_Omnibus.PNG?w=456&ssl=1" data-recalc-dims="1"></a></div>
<div></div>
<p>This is exactly the data format we need to perform our segmentation of the beverage category.</p>
<div><b>Conclusion: Respect the Munging!</b> </div>
<p>In this post, we took consumer review data about beverages and did an extensive data munging exercise in order to distill the information into a smaller, tidy dataset which we will use for analysis. We first examined the review dataset and the perceptions dataset and understood their structure. We next transformed the perceptions dataset from the long to the wide format, and coded the perceptions with numeric values. We then merged the review and perceptions data together to create a review-level dataset with data from both sources. Finally, we aggregated the review-level dataset to the beverage level, creating a single dataset which contains information on ratings, perceptions, category and number of reviews per beverage. After all of this work, we now have a dataset that we can use to analyze the different beverages!</p>
<p>Data munging and data analysis go hand-in-hand, and we can’t do any analyses without first getting our data in shape. While impressive modeling and visualization will probably always attract more attention, I’m glad I took the time to devote a post to data munging, the less-glamorous-but-equally-important component of any good data analysis.</p>
<p>In the next post, I will describe some analyses I have done on the dataset created here, in order to understand consumer perceptions of products within the beverage category. Stay tuned!</p>
	<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://methodmatters.blogspot.com/2017/08/showing-some-respect-for-data-munging.html"> Method Matters</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/-ISAtllnU3Q" height="1"></a></div>