<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/defining-marketing-with-the-rvest-and-tidytext-packages/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://r.prevos.net/rvest-and-tidytext/"> The Devil is in the Data</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>I am preparing to facilitate another session of the marketing course for the <a rel="nofollow" href="https://www.latrobe.edu.au/courses/mba" target="_blank">La Trobe University MBA</a>. The first lecture delves into the definition of marketing. Like most other social phenomena, marketing is tough to define. Definitions of social constructs often rely on the perspective taken by the person or group writing the definition. As such, definitions also change over time. While a few decades ago, definitions of marketing revolved around sales and advertising, <a rel="nofollow" href="https://www.ama.org/AboutAMA/Pages/Definition-of-Marketing.aspx" target="_blank">contemporary definitions</a> are more holistic and reference creating value.</p>
<p>Heidi Cohen wrote a blog post where she collated 72 definitions of marketing. So rather than arguing over which definition is the best, why not use all definitions simultaneously? This article attempts to define a new definition of marketing, using a data science approach. We can use the R language to scrape the 72 definitions from Heidi’s website and attempt text analysis to extract the essence of marketing from this data set.</p>
<p>I have mentioned in a previous post about <a rel="nofollow" href="https://r.prevos.net/qualitative-data-science/" target="_blank">qualitative data science</a> that automated text analysis is not always a useful method to extract meaning from a text. I decided to delve a little deeper into automated text analysis to see if we find out anything useful about marketing using the rvest and tidytext packages.</p>
<p>The presentation below shows the slides I use in my introductory lecture into marketing. The code and analyses are shown below the slideshow. You can download the most recent version of the code from my <a rel="nofollow" href="https://github.com/pprevos/r.prevos.net/tree/master/Marketing" target="_blank">GitHub</a> Repository.</p>
<p> </p>
<h2>Scraping text with Rvest</h2>
<p>Web scraping is a common technique to download data from websites where this data is not available as a clean data source. Web scraping starts with downloading the HTML code from the website and the filtering the wanted text from this file. The <a rel="nofollow" href="https://cran.r-project.org/web/packages/rvest/" target="_blank">rvest package</a> makes this process very easy.</p>
<p>The code for this article uses a pipe (<code>%>%</code>) with three rvest commands. The first step is to download the wanted html code from the web using the <code>read_html</code> function. The output of this function is piped to the <code>html_nodes</code> function, which does all the hard work. In this case, the code picks all lines of text that are embedded in an <code><ol><li> container, i.e. ordered lists. You can use the <a rel="nofollow" href="http://selectorgadget.com/" target="_blank">SelectorGadget</a> to target the text you like to scrape. The last scraping step cleans the text by piping the output of the previous commands to the <code>html_text</code> function.
<p>The result of the scraping process is converted to a <a rel="nofollow" href="https://tibble.tidyverse.org/" target="_blank">Tibble</a>, which is a type of data frame used in the Tidyverse. The definition number is added to the data, and the Tibble is converted to the format required by the Tidytext package. The resulting data frame is much longer than the 72 definitions because there are other lists on the page. Unfortunately, I could not find a way to filter only the 72 definitions.</p>
<pre>
library(tidyverse)
library(rvest)
definitions &lt;- read_html(&quot;https://heidicohen.com/marketing-definition/&quot;) %>%
    html_nodes(&quot;ol li&quot;) %>%
    html_text() %>%
    as_data_frame() %>%
    mutate(No = 1:nrow(.)) %>%
    select(No, Definition = value)
</pre>
<h2>Tidying the Text</h2>
<p>The <a rel="nofollow" href="https://www.tidytextmining.com/" target="_blank">Tidytext</a> package extends the <a rel="nofollow" href="http://vita.had.co.nz/papers/tidy-data.html" target="_blank">tidy data</a> philosophy to a text. In this approach to text analysis, a corpus consists of a data frame where each word is a separate item. The code snippet below takes the first 72 rows and the <code>unnest_tokens</code> function extracts each word from the 72 definitions. This function can also extract ngrams and other word groups from the text. The Tidytext package is an extremely versatile piece of software which goes far beyond the scope of this article. Julia Silge and David Robinson have written a book about <a rel="nofollow" href="https://www.tidytextmining.com/" target="_blank">text mining</a> using this package, which provides a very clear introduction to the craft of analysing text.</p>
<p>The last section of the pipe removes the trailing “s” from each word to convert plurals into single words. The mutate function in the Tidyverse creates or recreates a new variable in a data frame.</p>
<pre>
library(tidytext)
def_words &lt;- definitions[1:72, ] %>%
    unnest_tokens(word, Definition) %>%
    mutate(word = gsub(&quot;s$&quot;, &quot;&quot;, word))
</pre>
<p>This section creates a data frame with two variables. The No variable indicates the definition number (1–72) and the word variable is a word within the definition. The order of the words is preserved in the row name. To check the data frame you can run <code>unique(def_words$No[which(def_words$word == &quot;marketing&quot;)])</code>. This line finds all definition numbers with the word “marketing”, wich results, as expected, in the number 1 to 72.</p>
<h2>Using Rvest and Tidytext to define marketing</h2>
<p>We can now proceed to analyse the definitions scraped from the website with Rvest and cleaned with Tidytext. The first step is to create a word cloud, which is a popular way to visualise word frequencies. This code creates a data frame for each unique word, excluding the word marketing itself, and uses the wordcloud package to visualise the fifty most common words.</p>
<pre>
library(wordcloud)
library(RColorBrewer)

word_freq &lt;- def_words %>%
    anti_join(stop_words) %>%
    count(word) %>%
    filter(word != &quot;marketing&quot;)

word_freq %>%
    with(wordcloud(word, n, max.words = 50, rot.per = .5,
                   colors = rev(brewer.pal(5, &quot;Dark2&quot;))))
</pre>
<p><a rel="nofollow" href="https://r.prevos.net/?attachment_id=1400" target="_blank"><img data-orig-file="https://i1.wp.com/r.prevos.net/wp-content/uploads/sites/11/2018/05/marketingcloud-1.png?fit=1084%2C1193&amp;ssl=1" data-orig-size="1084,1193" data-medium-file="https://i1.wp.com/r.prevos.net/wp-content/uploads/sites/11/2018/05/marketingcloud-1.png?fit=273%2C300&amp;ssl=1" data-attachment-id="1400" data-image-meta="{" data-image-description="" src="https://i1.wp.com/r.prevos.net/wp-content/uploads/sites/11/2018/05/marketingcloud-1.png?resize=468%2C515&ssl=1" data-permalink="https://r.prevos.net/rvest-and-tidytext/marketingcloud-2/" data-large-file="https://i1.wp.com/r.prevos.net/wp-content/uploads/sites/11/2018/05/marketingcloud-1.png?fit=676%2C744&amp;ssl=1" alt="Defining Marketing with the Rvest and Tidytext Packages: Word cloud" data-image-title="marketingcloud" sizes="(max-width: 468px) 100vw, 468px" width="450" data-comments-opened="1" class="wp-image-1400" data-recalc-dims="1"></a></p>
<p>While a word cloud is certainly a pretty way to visualise the bag of words in a text, it is not the most useful way to get the reader to understand the data. The words are jumbled, and the reader needs to search for meaning. A better way to visualise word frequencies is a bar chart. This code takes the data frame created in the previous snippet, determines the top ten occurring words. The mutate statement reorders to factor levels so that the words are plotted in order.</p>
<pre>
word_freq %>%
    top_n(10) %>%
    mutate(word = reorder(word, n)) %>%
    ggplot(aes(word, n)) + 
        geom_col(fill = &quot;dodgerblue4&quot;) +
        coord_flip() +
        theme(text = element_text(size=20))
</pre>
<p><a rel="nofollow" href="https://r.prevos.net/?attachment_id=1401" target="_blank"><img data-orig-file="https://i2.wp.com/r.prevos.net/wp-content/uploads/sites/11/2018/05/marketingtop10words.png?fit=2096%2C2097&amp;ssl=1" data-orig-size="2096,2097" data-medium-file="https://i2.wp.com/r.prevos.net/wp-content/uploads/sites/11/2018/05/marketingtop10words.png?fit=300%2C300&amp;ssl=1" data-attachment-id="1401" data-image-meta="{" data-image-description="" src="https://i2.wp.com/r.prevos.net/wp-content/uploads/sites/11/2018/05/marketingtop10words.png?resize=594%2C594&ssl=1" data-permalink="https://r.prevos.net/rvest-and-tidytext/marketingtop10words/" data-large-file="https://i2.wp.com/r.prevos.net/wp-content/uploads/sites/11/2018/05/marketingtop10words.png?fit=676%2C676&amp;ssl=1" alt="Defining Marketing with the Rvest and Tidytext Packages: bar chart" data-image-title="marketingtop10words" sizes="(max-width: 594px) 100vw, 594px" width="450" data-comments-opened="1" class="wp-image-1401" data-recalc-dims="1"></a></p>
<p>A first look at the word cloud and bar chart suggests that marketing is about customers and products and services. Marketing is a process that includes branding and communication; a simplistic but functional definition.</p>
<h2>Topic Modeling using Tidytext</h2>
<p>Word frequencies are a weak method to analyse text because it interprets each word as a solitary unit. Topic modelling is a more advanced method that analyses the relationships between words, i.e. the distance between them. The first step is to create a <a rel="nofollow" href="https://en.wikipedia.org/wiki/Document-term_matrix" target="_blank">Document-Term Matrix</a>, which is a matrix that indicates how often a word appears in a text.  As each of the 72 texts are very short, I decided to treat the collection of definitions as one text about marketing. The cast_dtm function converts the data frame to a Document-Term Matrix.</p>
<p>The following pipe determines the top words in the topics. Just like k-means clustering, the analyst needs to choose the number of topics before analysing the text. In this case, I have opted for 4 topics. The code determines the contribution of each word to the four topics and selects the five most common words in each topic. The faceted bar chart shows each of the words in the four topics.</p>
<pre>
marketing_dtm &lt;- word_freq %>%
    mutate(doc = 1) %>%
    cast_dtm(doc, word, n)

marketing_lda &lt;- LDA(marketing_dtm, k = 4) %>%
    tidy(matrix = &quot;beta&quot;) %>%
    group_by(topic) %>%
    top_n(5, beta) %>%
    ungroup() %>%
    arrange(topic, -beta)

marketing_lda %>%
    mutate(term = reorder(term, beta)) %>%
    ggplot(aes(term, beta, fill = factor(topic))) +
       geom_col(show.legend = FALSE) +
       facet_wrap(~topic, scales = &quot;free&quot;) +
       coord_flip() +
       theme(text = element_text(size=20))
</pre>
<p>This example also does not tell me much more about what marketing is, other than giving a slightly more sophisticated version of the word frequency charts. This chart shows me that marketing is about customers that enjoy a service and a product. Perhaps the original definitions are not distinctive enough to be separated from each other. The persistence of the word “president” is interesting as it seems to suggest that marketing is something that occurs at the highest levels in the business.</p>
<p><a rel="nofollow" href="https://r.prevos.net/?attachment_id=1402" target="_blank"><img data-orig-file="https://i2.wp.com/r.prevos.net/wp-content/uploads/sites/11/2018/05/MarketingTopics.png?fit=2100%2C2100&amp;ssl=1" data-orig-size="2100,2100" data-medium-file="https://i2.wp.com/r.prevos.net/wp-content/uploads/sites/11/2018/05/MarketingTopics.png?fit=300%2C300&amp;ssl=1" data-attachment-id="1402" data-image-meta="{" data-image-description="" src="https://i2.wp.com/r.prevos.net/wp-content/uploads/sites/11/2018/05/MarketingTopics.png?resize=586%2C586&ssl=1" data-permalink="https://r.prevos.net/rvest-and-tidytext/marketingtopics/" data-large-file="https://i2.wp.com/r.prevos.net/wp-content/uploads/sites/11/2018/05/MarketingTopics.png?fit=676%2C676&amp;ssl=1" alt="Defining Marketing with the Rvest and Tidytext Packages: Topic modeling" data-image-title="MarketingTopics" sizes="(max-width: 586px) 100vw, 586px" width="450" data-comments-opened="1" class="wp-image-1402" data-recalc-dims="1"></a><br>
This article is only a weak summary of the great work by Julia Silge who coauthored the Tidytext package. The video below provides a comprehensive introduction to topic modelling.</p>
<p><iframe allowfullscreen="true" src="https://www.youtube.com/embed/evTuL-RcRpc?version=3&rel=1&%23038;fs=1&%23038;autohide=2&%23038;showsearch=0&%23038;showinfo=1&%23038;iv_load_policy=1&%23038;wmode=transparent" width="450" type="text/html"></iframe></p>
<h2>What have we learnt?</h2>
<p>This excursion into text analysis using rvest and Tidytext shows that data science can help us to make some sense out of an unread text. If I did not know what this page was about, then perhaps this analysis would enlighten me. This kind of analysis can assist us in wading through to large amounts of text to select the ones we want to read. I am still not convinced that this type of analysis will provide any knowledge beyond what can be obtained from actually reading and engaging with a text.</p>
<p>Although I am a data scientist and want to maximise the use of code in analysing data, I am very much in favour of developing human intelligence before we worry about the artificial kind.</p>
<p>The post <a rel="nofollow" href="https://r.prevos.net/rvest-and-tidytext/" target="_blank">Defining Marketing with the Rvest and Tidytext Packages</a> appeared first on <a rel="nofollow" href="https://r.prevos.net/" target="_blank">The Devil is in the Data</a>.</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="https://r.prevos.net/rvest-and-tidytext/"> The Devil is in the Data</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 alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/H5jNCHrCAEI" height="1"></a></div></ol></code>