<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/turning-keywords-into-a-co-occurrence-network/"></div></div><div><a data-url="https://www.r-bloggers.com/turning-keywords-into-a-co-occurrence-network/" data-counturl="https://www.r-bloggers.com/turning-keywords-into-a-co-occurrence-network/" data-count="horizontal" data-text="Turning keywords into a co-occurrence network" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://f.briatte.org/r/turning-keywords-into-a-co-occurrence-network"> R / Notes</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>This post is addressed to the <a target="_blank" href="http://www.sciencespo.fr/ecole-urbaine/en/glm">GLM</a> Fall 2016 students who are currently taking my <a target="_blank" href="http://f.briatte.org/teaching/quanti/">Statistical Reasoning and Quantitative Methods</a> course at Sciences Po in Paris.</p>
<h2>Dear students</h2>
<p>Since you are going to learn a lot of statistical computing/programming this semester, I thought it would be a good idea to show you a quick example of what you can achieve with those skills if you continue learning them beyond the scope of our course.</p>
<p>The demo below uses a different programming language than the one that you are learning to use: instead of the Stata/Mata language used by the <a target="_blank" href="http://www.stata.com/">Stata</a> software that we use in class, this post shows you how to use the <a target="_blank" href="https://www.r-project.org/">R</a> language. The R language has a steeper learning curve, but it is also much more versatile than the Stata language.</p>
<p><strong>tl;dr</strong> – This note explains how to plot this graph in less than 70 lines of code:</p>
<p><img alt="bordered" src="https://i1.wp.com/f.briatte.org/r/images/turning-keywords-into-a-co-occurrence-network.png?w=456" data-recalc-dims="1"></p>
<h2>The data: Your keywords</h2>
<p>In our second class together, I suggested that you fill in a Google Sheet with your names, and with the keywords that represent your main research interests, as in:</p>
<pre><code>François: Public Policy, Health Systems, Health Inequalities
</code></pre>
<p>Taking advantage of the fact that your class is a small one and that there are no duplicates among your first names, I have anonymized the data that you submitted by keeping only those first names to identify you in it.</p>
<p>Furthermore, I have cleaned up your keywords by capitalizing them and by harmonizing them a bit, e.g. coding “Spatial Inequalities” as “Spatial Inequality” everywhere where that combination of keywords appears.</p>
<p>The result is that dataset, which has only two columns, i.e. only two variables (<code>name</code> and <code>keywords</code>), separated by a <a target="_blank" href="https://en.wikipedia.org/wiki/Tab_key">tab</a> (<code>\t</code>) character:</p>
<p></p>
<p>The data contain 18 rows—a header row, and one row per student. It’s a small dataset, but it is also highly representative of your student group, since all of you filled in the table. Still, the <em>sample</em> of students shown here is only a sample from the <em>target population</em> (GLM students in year 2016), because that population might (marginally) vary throughout the academic year.</p>
<p>Going through the data, you will notice that some of your keywords are shorter than those that you submitted: “Community/Neighborhood Initiatives,” for instance, has been turned into simply “Community/Neighborhood.” This is because we are going to visualize the keywords into a particular kind of plot in which long <a target="_blank" href="https://en.wikipedia.org/wiki/String_(computer_science)">text strings</a> like that one will be problematic to read.</p>
<p>You will also notice that some keywords have been radically altered: I have replaced “Environmental Initiatives” by “Environment,” and “Social Movements” by “Collective Action.” This is because I believe those pairs of keywords designate similar things—so the data inevitably contain some interpretation introduced by the coder (myself), and might therefore differ from what is meant to be measured (your interests).</p>
<h2>The concept: A network of keyword co-occurrences</h2>
<h3>From keyword co-occurrences…</h3>
<p>Some of the keywords that you provided are very precise, others are more vague. What we are going to do now is to find which keywords are more frequent, and also find out which keywords were cited together in the individual lists that you submitted.</p>
<p>Every time a student mentioned two keywords together in his or her list (i.e. a keyword <em>co-occurrence</em>), we are going to create an <em>undirected tie</em> between those keywords, as in</p>
<pre><code>Gender---Inequality
Inequality---Gender
</code></pre>
<p>The undirected nature of the tie means that the two examples above are treated as identical: the direction of the tie is insignificant.</p>
<p>Note that we are going to treat as co-occurrences the situation where two keywords are listed together by a student with a comma between them, as in <code>Gender, Inequality</code>, but <em>also</em> the situation where two keywords appear separated by the “and” <a target="_blank" href="https://en.wikipedia.org/wiki/Conjunction_(grammar)">conjunction</a>, as in “Gender and Inequality.”</p>
<p>This last rule, which is arbitrary, will consequently ignore the “Gender and Race” association that several students included in their list of keywords, and treat it as if the students had listed the keywords separately as “Gender, Race.” Data preparation always implies some simplification, which is what is happening here.</p>
<h3>… to a network of co-occurrences</h3>
<p>The data contain several keywords that appear on more than one row, so the aggregation of all the different ties that we are going to create will produce a list of connections between keywords – which we will call an <em><a target="_blank" href="https://en.wikipedia.org/wiki/Adjacency_list">edge list</a></em> – in which some ties will appear more than once.</p>
<p>At that stage, if you are familiar with <a target="_blank" href="https://en.wikipedia.org/wiki/Network_theory">network theory</a>, you should be thinking: this is going to be a <em>weighted one-mode network</em>—<em>weighted</em> because each tie in the edge list will be valued by a positive number that indicates its frequency, and <em>one-mode</em> because the edge list contains only one kind of entity (keywords).</p>
<p>If you are not familiar with network theory, which I assume is the case, just read on, see what happens, and use your intuition to understand what we will be doing.</p>
<h2>Back to the data</h2>
<p>Let’s now introduce our first snippet of R of code, which reads the tab-separated data shown a few paragraphs above, splits it into individual keywords, aggregates and counts those keywords, and orders those that appear more than once into a list ordered by decreasing frequency:</p>
<p></p>
<p>I am not going to explain how the code works in detail, but if you just read through it, you might guess that the first line, <a target="_blank" href="http://www.rdocumentation.org/packages/readr/versions/1.0.0/topics/read_delim"><code>read_tsv</code></a>, is a command – or more exactly, a <em>function</em> – that reads <a target="_blank" href="https://en.wikipedia.org/wiki/Tab-separated_values">tab-separated (TSV)</a> data.</p>
<p>The same line of the code extracts the <em>keywords</em> column from that data, which is then <a target="_blank" href="http://www.rdocumentation.org/packages/stringr/versions/1.1.0/topics/str_split">split</a> by the second line of code everywhere where a comma or the “and” conjunction appear. The next three lines of code (<code>unlist</code>, <code>table</code> and <code>data.frame</code>) are just data manipulation operations that you can skip.</p>
<p>The final lines of code sort the data by decreasing frequency and show those keywords that appear more than once. The full result is shown below:</p>
<pre><code>                    . Freq
1              Gender    8
2          Inequality    6
3           Migration    6
4         Environment    4
5             Poverty    4
6                Race    4
7      Transportation    3
8       Urban Studies    3
9   Collective Action    2
10            Housing    2
11       Human Rights    2
12           Politics    2
13           Religion    2
14 Spatial Inequality    2
</code></pre>
<p>The result tells you that most frequent keyword in the data is “Gender,” closely followed by “Inequality” and “Migration.” The result also tells you that, out of all the keywords that you submitted, 14 of them appear more than once. With slightly different code, we could establish that there are also 20 single-occurring keywords in the data.</p>
<h2>Building a weighted edge list</h2>
<blockquote>
<p>This section is quite technical. Just skip it if you are only interested in the final result.</p>
</blockquote>
<p>Let’s turn the keyword co-occurrences into a weighted edge list. To do that, we extract your lists of keywords again, which we then turn into a list of <a target="_blank" href="http://www.rdocumentation.org/packages/base/versions/3.3.1/topics/expand.grid">all possible combinations</a> between them, collating the final result into a single object:</p>
<p></p>
<p>The code above is quite esoteric: even if you are very familiar with R code, some bits of it might be a bit obscure. Do not focus on the code, and take a look at this extract from the result instead:</p>
<pre><code>                            X1                         X2         w
1                  Development                Development 0.2000000
2                   Corruption                Development 0.2000000
3                  Development                    Housing 0.2000000
.
.
.
222          Collective Action      Immigrant Integration 0.2000000
223          Collective Action          Collective Action 0.2000000
224                Environment                Environment 0.3333333
225          Collective Action                Environment 0.3333333
226                Environment              Urban Studies 0.3333333
</code></pre>
<p>The <code>e</code> data object that we have created is a weighted edge list: the first two columns, <code>X1</code> and <code>X2</code>, are keywords that appear together in your lists, and the last column <code>w</code> is a weighting factor that controls for the total number of keywords $N$ submitted by each student by taking its inverse value $1 / N$.</p>
<p>Note that the <code>X1</code> and <code>X2</code> columns contain alphabetically-sorted keywords: the first column always holds a keyword of lower alphabetical order than the one held in the second column. This trick ensures that we will treat the keyword associations $(i, j)$ and $(j, i)$ as the same association, since our edge list contains only undirected ties.</p>
<p>Also note that some rows hold something known as “self-loops,” i.e. keywords that are “connected to themselves.” In this precise context, these loops are meaningless and will be dropped at the end of our next step:</p>
<p></p>
<p>This bit of the code aggregates all ties together by summing their weights, so that every unique association of keywords $(X1, X2)$ now has the weight $W_{X1, X2} = \sum{1 / N}$, where the $1 / N$ fraction designates the value that we previously established as the weighting factor of a single edge, or tie between keywords $X1$ and $X2$.</p>
<p>I call the result of this weighting technique “<a target="_blank" href="http://www-personal.umich.edu/~mejn/">Newman</a>–<a target="_blank" href="http://jhfowler.ucsd.edu/">Fowler</a> weights” in reference to two scientists, one physicist and one political scientist, who used it in a series of papers on <a target="_blank" href="http://www-personal.umich.edu/~mejn/collaboration/index.html">scientific collaboration</a> and <a target="_blank" href="http://jhfowler.ucsd.edu/cosponsorship.htm">legislative cosponsorship</a> respectively.</p>
<p>See my <a target="_blank" href="http://f.briatte.org/r/weighting-authorship-networks">note on weighting co-authorship networks</a> for more details on the kind of edge weights that I am using here.</p>
<h2>Building a weighted network</h2>
<blockquote>
<p>This section is also quite technical. Just skip it if you are only interested in the final result.</p>
</blockquote>
<p>The next part of the R code is even more esoteric than the previous parts of the code, because we are now going to turn the edge list <code>e</code> into the undirected network <code>n</code>, which will contain keywords connected by ties indicating when these keywords were listed together:</p>
<p></p>
<p>The code above has also weighted the network edges (i.e. its ties), and used these edge weights to compute the <a target="_blank" href="http://www.rdocumentation.org/packages/tnet/versions/3.0.14/topics/degree_w">weighted degree</a> of each <a target="_blank" href="https://en.wikipedia.org/wiki/Vertex_(graph_theory)">vertex</a> (or <em>node</em>) of the network, using a formula by <a target="_blank" href="https://toreopsahl.com/">Tore Opsahl</a>, a scientist who <a target="_blank" href="https://toreopsahl.com/about/">currently works</a> at the Bank of America.</p>
<p>“Weighted degree” stands for a network measure that reflects the <a target="_blank" href="https://en.wikipedia.org/wiki/Centrality">centrality</a> of the nodes in a network. In our co-occurrence network of keywords, those keywords that are connected to many other keywords will have a higher degree, which will be useful to visualize the keywords that were frequently listed.</p>
<p>Since we are using a weighted degree measure, the fact some students listed more keywords than others is controlled for by the $1/N$ inverse-sum factor that we described above. The weighting method that we are using is not perfect, but it is good enough for our exploratory purposes.</p>
<h2>Visualizing the network</h2>
<p>We are now only two steps from the final result. The last technical step that I want to take is to label only the most important keywords of the network, in order to avoid having too much information in my final plot. I will do this by hiding keywords with a low weighted degree:</p>
<p></p>
<p>And finally, let’s plot the network using the <a target="_blank" href="http://ggplot2.org/"><code>ggplot2</code></a> “grammar of graphics” syntax, in combination with <a target="_blank" href="http://f.briatte.org/r/ggnetwork-network-geometries-for-ggplot2">some code that I wrote</a> to have this syntax work with network objects like the one that I built in the previous parts of the text:</p>
<p></p>
<p>Here’s the result, which is also shown at the top of this note. The network is composed of nodes (keywords), connected by ties (co-occurrences). The placement of the nodes was obtained from a <a target="_blank" href="https://en.wikipedia.org/wiki/Force-directed_graph_drawing">force-directed placement algorithm</a> that attracts nodes with strong ties and repulses those with no ties.</p>
<p><img alt="bordered" src="https://i1.wp.com/f.briatte.org/r/images/turning-keywords-into-a-co-occurrence-network.png?w=456" data-recalc-dims="1"></p>
<p>In the plot, nodes with higher degrees have larger labels, and the strongest ties between the nodes are darker than other ties. The nodes represented as points instead of labels are keywords with low weighted degree values. These nodes, which are not central to the network, are logically located at the periphery of the graph.</p>
<h2>Final comments</h2>
<p>Looking at this graph, what can we say substantively about the research interests of this year’s batch of GLM students?</p>
<p>It seems clear that the main thematic nexus in the network is composed of “Race and Gender” combined to “Migration, Inequality and Poverty.” In the students’ minds, “Inequality” probably equates to “Economic Inequality,” as other kinds of inequalities appear as different, better-specified keywords.</p>
<p>The top of the graph also shows a cluster of keywords connected to the “Environment” keyword, and the bottom of the graph shows another cluster connected to the “Transport” keyword, oddly connected to the more central keywords by the “Religion” keyword, which acts as a partial bridge here.</p>
<p>From a substantive point of view, I would say that this graph shows a very surprising disconnect between environmental and transportation issues: both issues are often very tightly connected in real life, especially in urban settings where <a target="_blank" href="https://en.wikipedia.org/wiki/Public_transport">public transportation</a> is generally promoted as a way to reduce airborne pollution.</p>
<hr>
<p>The code shown in this not is provided in full in <a target="_blank" href="https://gist.github.com/briatte/7b9b70859a4bd5ff7ec6ddda6452e516">this Gist</a>. If you want to replicate the plot above, you will need to <a target="_blank" href="https://gist.github.com/briatte/7b9b70859a4bd5ff7ec6ddda6452e516#file-0_keywords-txt">download the data</a> and (install and) <a target="_blank" href="https://gist.github.com/briatte/7b9b70859a4bd5ff7ec6ddda6452e516#file-1_packages-r">load the required packages</a> first.</p>
<p><div><div><div><div data-width="55" data-show-faces="false" data-send="true" data-layout="box_count" data-height="62" data-href="https://www.r-bloggers.com/turning-keywords-into-a-co-occurrence-network/"></div></div><div><a data-url="https://www.r-bloggers.com/turning-keywords-into-a-co-occurrence-network/" data-counturl="https://www.r-bloggers.com/turning-keywords-into-a-co-occurrence-network/" data-count="vertical" data-text="Turning keywords into a co-occurrence network" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://f.briatte.org/r/turning-keywords-into-a-co-occurrence-network"> R / Notes</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/?s=tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/?s=data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/?s=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/?s=ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/?s=map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/?s=animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/?s=RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/?s=sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/?s=LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/?s=SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/?s=eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/?s=git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/?s=hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/?s=Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/?s=PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/?s=time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/?s=trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/JHu-mNr-ekI"></a></div>