<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mihiretu M Kebede (PhD) on Medium]]></title>
        <description><![CDATA[Stories by Mihiretu M Kebede (PhD) on Medium]]></description>
        <link>https://medium.com/@drkebede?source=rss-7dc19c3314ec------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8GbxmlVZ2TU0PuNAOjvovw.jpeg</url>
            <title>Stories by Mihiretu M Kebede (PhD) on Medium</title>
            <link>https://medium.com/@drkebede?source=rss-7dc19c3314ec------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 13:53:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@drkebede/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Inverse Probability Weighting and Marginal Structural Models: a comprehensive tutorial]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://drkebede.medium.com/inverse-probability-weighting-and-marginal-structural-models-comprehensive-tutorial-91bd01de62c6?source=rss-7dc19c3314ec------2"><img src="https://cdn-images-1.medium.com/max/1556/0*Lz-w81R2hMrPBZzn.png" width="1556"></a></p><p class="medium-feed-snippet">Introduction</p><p class="medium-feed-link"><a href="https://drkebede.medium.com/inverse-probability-weighting-and-marginal-structural-models-comprehensive-tutorial-91bd01de62c6?source=rss-7dc19c3314ec------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://drkebede.medium.com/inverse-probability-weighting-and-marginal-structural-models-comprehensive-tutorial-91bd01de62c6?source=rss-7dc19c3314ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/91bd01de62c6</guid>
            <category><![CDATA[causal-inference]]></category>
            <category><![CDATA[epidemiology]]></category>
            <category><![CDATA[real-world-evidence]]></category>
            <category><![CDATA[propensity-score-matching]]></category>
            <category><![CDATA[clinical-research]]></category>
            <dc:creator><![CDATA[Mihiretu M Kebede (PhD)]]></dc:creator>
            <pubDate>Fri, 27 Feb 2026 09:49:14 GMT</pubDate>
            <atom:updated>2026-02-27T09:55:09.227Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[RWE Data Analysis Using Propensity Score Matching (PSM): Concept, Implementation, and…]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://drkebede.medium.com/rwe-data-analysis-using-propensity-score-matching-psm-concept-implementation-and-d419d8a8d5a4?source=rss-7dc19c3314ec------2"><img src="https://cdn-images-1.medium.com/max/1248/0*6OZGEzFU1rEGm7b7.png" width="1248"></a></p><p class="medium-feed-snippet">Introduction</p><p class="medium-feed-link"><a href="https://drkebede.medium.com/rwe-data-analysis-using-propensity-score-matching-psm-concept-implementation-and-d419d8a8d5a4?source=rss-7dc19c3314ec------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://drkebede.medium.com/rwe-data-analysis-using-propensity-score-matching-psm-concept-implementation-and-d419d8a8d5a4?source=rss-7dc19c3314ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/d419d8a8d5a4</guid>
            <category><![CDATA[causal-inference]]></category>
            <category><![CDATA[epidemiology]]></category>
            <category><![CDATA[propensity-score-matching]]></category>
            <category><![CDATA[rstats]]></category>
            <dc:creator><![CDATA[Mihiretu M Kebede (PhD)]]></dc:creator>
            <pubDate>Fri, 05 Dec 2025 20:57:35 GMT</pubDate>
            <atom:updated>2025-12-05T20:57:35.484Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Still presenting regression results in tables? Why not forest plots?]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://drkebede.medium.com/still-presenting-regression-results-in-tables-why-not-forest-plots-bb5715b34341?source=rss-7dc19c3314ec------2"><img src="https://cdn-images-1.medium.com/max/780/0*X5TnA4eMJ2G9Pm_4.jpg" width="780"></a></p><p class="medium-feed-snippet">Why Are We Still Using Endless Tables?</p><p class="medium-feed-link"><a href="https://drkebede.medium.com/still-presenting-regression-results-in-tables-why-not-forest-plots-bb5715b34341?source=rss-7dc19c3314ec------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://drkebede.medium.com/still-presenting-regression-results-in-tables-why-not-forest-plots-bb5715b34341?source=rss-7dc19c3314ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb5715b34341</guid>
            <category><![CDATA[forest-plot]]></category>
            <category><![CDATA[data-vizualisation]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[regression]]></category>
            <dc:creator><![CDATA[Mihiretu M Kebede (PhD)]]></dc:creator>
            <pubDate>Fri, 10 Oct 2025 06:59:13 GMT</pubDate>
            <atom:updated>2025-10-10T06:59:13.673Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Title: Understanding min, max, pmin, and pmax in dplyr: Avoiding Common Pitfalls When Mutating New…]]></title>
            <link>https://drkebede.medium.com/title-understanding-min-max-pmin-and-pmax-in-dplyr-avoiding-common-pitfalls-when-mutating-new-32e818624a8b?source=rss-7dc19c3314ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/32e818624a8b</guid>
            <category><![CDATA[data-manipulation]]></category>
            <category><![CDATA[r]]></category>
            <dc:creator><![CDATA[Mihiretu M Kebede (PhD)]]></dc:creator>
            <pubDate>Fri, 16 Aug 2024 08:18:49 GMT</pubDate>
            <atom:updated>2024-08-16T08:18:49.577Z</atom:updated>
            <content:encoded><![CDATA[<p>Title: Understanding min, max, pmin, and pmax in dplyr: Avoiding Common Pitfalls When Mutating New Variables in dplyr</p><p>I recently got stumbled on this and I found it important to know the use of min, max, pmin and pmax when mutating a new variable using dplyr. When working with larger datasets in R, particularly using the dplyr package, it&#39;s essential to carefully choose functions when mutating new variables from existing columns. Functions like min(), max(), pmin(), and pmax() each behave differently, and selecting the wrong one can lead to incorrect results. This is especially important when dealing with larger datasets with many columns.</p><h4>The Basics: min() and max()</h4><p>The min() and max() functions in R return the minimum and maximum values, respectively, across a set of inputs. However, when used inside a mutate() call in dplyr, these functions might not behave as expected.</p><p>Let’s consider an example with a dataset that contains 10 columns (A to J) and 100 rows:</p><pre>library(dplyr)</pre><pre># Example dataset<br>df &lt;- data.frame(<br> A = sample(1:100, 100, replace = TRUE),<br> B = sample(1:100, 100, replace = TRUE),<br> C = sample(1:100, 100, replace = TRUE),<br> D = sample(1:100, 100, replace = TRUE),<br> E = sample(1:100, 100, replace = TRUE),<br> F = sample(1:100, 100, replace = TRUE),<br> G = sample(1:100, 100, replace = TRUE),<br> H = sample(1:100, 100, replace = TRUE),<br> I = sample(1:100, 100, replace = TRUE),<br> J = sample(1:100, 100, replace = TRUE)<br>)</pre><pre># Using min() inside mutate<br>df &lt;- df %&gt;%<br> mutate(min_val = min(A, B, C, D, E, F, G, H, I, J))</pre><p>Here, instead of computing the row-wise minimum across columns A to J, the min() function will return a single minimum value from all elements across the entire dataset, and every entry in the min_val column will have this value. This is because min() in this context is applied to the entire set of values as a single vector, not row-wise. This can be problematic if you are mutating a new variable from the values of selected variables.</p><h4>The Correct Approach: pmin() and pmax()</h4><p>For row-wise operations, pmin() and pmax() are the functions you need. They calculate the minimum or maximum values for each row across the specified columns.</p><pre>df &lt;- df %&gt;%<br> mutate(min_val = pmin(A, B, C, D, E, F, G, H, I, J),<br> max_val = pmax(A, B, C, D, E, F, G, H, I, J))</pre><p>In this case, min_val will correctly contain the minimum value across columns A to J for each row, and max_val will contain the maximum value.</p><h4>Common Pitfalls</h4><ol><li><strong>NA Handling</strong>: When working with NA values, min() and max() return NA if any NA is present in the input, unless you explicitly set na.rm = TRUE. However, pmin() and pmax() will only return NA if all the values in the row are NA. This can lead to unintended results if not carefully managed.</li><li><strong>Incorrect Aggregation</strong>: As illustrated above, using min() or max() inside mutate() without considering their scope can lead to unintended aggregation across the entire data frame rather than row-wise operations. This is a common mistake, especially when transitioning from base R to dplyr.</li><li><strong>Performance Considerations</strong>: While pmin() and pmax() perform the intended row-wise operations, they can be computationally more intensive than min() and max() when dealing with large datasets. However, the accuracy they provide in row-wise computation usually outweighs this performance concern.</li></ol><h4>Conclusion</h4><p>When mutating new variables in dplyr, it&#39;s crucial to use the appropriate functions for the task. While min() and max() are suitable for finding overall minimum and maximum values across the entire dataset, pmin() and pmax() should be used for row-wise operations. By understanding and correctly applying these functions, you can avoid common pitfalls and ensure accurate data manipulation, even with larger datasets.</p><p>Using the right approach will ensure that your data manipulation is both accurate and efficient, helping you make the most of your data analysis tasks in R.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32e818624a8b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Q: Is it possible to calculate the arithmetic mean from the geometric mean or vice versa?]]></title>
            <link>https://drkebede.medium.com/q-is-it-possible-to-calculate-the-arithmetic-mean-from-the-geometric-mean-or-vice-versa-09809eac739d?source=rss-7dc19c3314ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/09809eac739d</guid>
            <dc:creator><![CDATA[Mihiretu M Kebede (PhD)]]></dc:creator>
            <pubDate>Sun, 03 Dec 2023 13:13:12 GMT</pubDate>
            <atom:updated>2023-12-03T13:39:54.437Z</atom:updated>
            <content:encoded><![CDATA[<p>Q: Is it possible to calculate the arithmetic mean from the geometric mean or vice versa?</p><p>mean = mean(c(2, 4, 8, 16, 32))<br>sd= sd(c(2, 4, 8, 16, 32))<br>geom_mean = prod(c(2, 4, 8, 16, 32))^(1/5)</p><p>Now calculate the geometric mean from the summary data(mean, sd, variance, etc). Is it possible?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=09809eac739d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scraping individual participant data from scatter plots]]></title>
            <link>https://drkebede.medium.com/scraping-individual-participant-data-from-scatter-plots-5f1d312d50a3?source=rss-7dc19c3314ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f1d312d50a3</guid>
            <category><![CDATA[meta-analysis]]></category>
            <category><![CDATA[systematic-review]]></category>
            <category><![CDATA[scrapping]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Mihiretu M Kebede (PhD)]]></dc:creator>
            <pubDate>Fri, 21 Apr 2023 09:27:03 GMT</pubDate>
            <atom:updated>2023-04-21T09:27:03.561Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>A scatter plot aka scatter diagram is one of the most commonly used graphs to display the relationship between two or more variables. By looking at scatter plots, we can quickly have an insight into whether two or more variables are linearly, negatively/positively, or how strongly they are correlated to each other.</p><p>Scatter plots are often reported in scientific publications. Though many scientific publications report scatter plots to display relationships, correlation statistics may not be reported along with the scatter plots. Fortunately, scatter plots opens door to open science. With the help of new tools such as <a href="https://automeris.io/WebPlotDigitizer/"><em>WebPlotDigitizer</em></a> web-based point and click software, <a href="https://pypi.org/project/plotdigitizer/"><em>plotdigitizer python</em></a> python package, or the <a href="https://github.com/tpoisot/digitize">digitize</a> R packages, we can easily digitize scatter plots, scrap individual participant data and estimate correlation values. If you are working on systematic reviews, you may not find all relevant data from the reported papers. You either need to contact the authors or find out mechanisms for estimating values from reported data. I will be back on another blog post on estimating some values from reported data.</p><h3>How do we extract values?</h3><p>I will step by step demonstrate how you can easily extract individual participant data from a scatter plot of an old publication. For detailed explanations, please check the following YouTube video. <a href="https://www.youtube.com/watch?v=3NI4CyJzJhM&amp;t=344s">&lt;https://www.youtube.com/watch?v=3NI4CyJzJhM&amp;t=344s&gt;</a>. I often do R or Python data science tutorials and live coding sessions on my YouTube channel. Please consider subscribing. That will encourage me for sharing more content.</p><p>The scatter plot that I will use is from the 1994 publication by Strain G. and colleagues. The results are interesting and I invite you to read the paper.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Kt0hApuEeU-iTxqx.png" /></figure><p>For this blog post, I will be using Fig 1 which shows the relationship of fasting insulin level to BMI in non-dieting weight-stable subjects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/0*EkYndfzMz2CNtWmV.png" /></figure><p>Now, we have what we need and let’s go straight to extracting individual participant data from the scatter plot.</p><p>What we need to do is take a screen shot of the scatter plot, save it as png or JPG, read it in R, calibrate the x and y axes .</p><h3>Read and calibrate the figure (mark the beginning and the end of x and y axis)</h3><pre>library(digitize)<br>fig &lt;- ReadAndCal(&#39;F:/github/githubwebsite/_posts/2021-06-07-scraping-individual-participant-data-from-scatter-plots/scatterPlotdigitize.JPG&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X0-PdWZeGxXCDGKL.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*p1CQLCwcC3VtDZmP.gif" /></figure><h3>Mark data points</h3><pre>data.points = DigitData(col=&#39;red&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*upbpGdnZk0yPWvXj.gif" /></figure><h3>Extract the data point in a data frame</h3><pre>df &lt;- Calibrate(data.points, fig, 0, 100, 0, 100) #determin where x and y axis values start and end</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GJ8UrXxEPT6WO4BU.gif" /></figure><p>Now we have extracted the x which was BMI and the y (insulin level). We can easily recalculate the correlation and Beta coefficient values.</p><pre>cor(df$x, df$y, method = &#39;pearson&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/0*FdlZgwkxXVb1wkHc.png" /></figure><p>Estimate the regression coefficient and compare with the reported value.</p><pre>summary(lm(y~x, data=df))</pre><p>I estimated the correlation value to be 0.709 and the Beta coefficient to be about 0.9605. The tiny difference is due to my calibration. If you zoom and carefully calibrate, you can have approximately similar values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BNjOzz71I1BhNgjQ.png" /></figure><p>Thank you for reading this post. I hope you find this helpful. For more, subscribe to my <a href="https://www.youtube.com/channel/UCpHd6O1Yqz4YgcYUBfyRqKg">YouTube channel</a> and follow me on Twitter @<a href="https://twitter.com/RPy_DataScience">RPy_DataScience</a>. You can also follow me by liking <a href="https://web.facebook.com/R_Py-Data-Science-105325938441990/news_feed">R_Py Data Science</a> Facebook page.</p><h3>Contact</h3><p>Please mention @<a href="https://twitter.com/RPy_DataScience">RPy_DataScience</a> if you tweet this post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f1d312d50a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quantile regression tutorial in R]]></title>
            <link>https://drkebede.medium.com/quantile-regression-tutorial-in-r-f2eec72c132b?source=rss-7dc19c3314ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2eec72c132b</guid>
            <category><![CDATA[quantile-regression]]></category>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[vizualization]]></category>
            <dc:creator><![CDATA[Mihiretu M Kebede (PhD)]]></dc:creator>
            <pubDate>Fri, 21 Apr 2023 09:21:35 GMT</pubDate>
            <atom:updated>2023-04-21T09:21:35.731Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Motivation</strong></h4><h4>Around a year ago, a subscriber on my YouTube channel requested that I create a video on “Quantile regression”. Although I had no prior experience with this regression technique, I accepted the assignment and began researching the topic. After gaining a basic understanding of the technique, I created a video that was well-received by my audience and has since become one of my most viewed videos. You can watch it here: <a href="https://www.youtube.com/watch?v=BPDr-BbRfK0&amp;ab_channel=R_PyDataScience">https://www.youtube.com/watch?v=BPDr-BbRfK0&amp;ab_channel=R_PyDataScience</a>.</h4><h4>Several viewers have also requested that I make the code available, and I apologize for the delay in doing so due to time constraints. Better than never, I will share the code today. Thanks for your patience.</h4><h3>What is quantile regression?</h3><p>Quantile regression is a statistical technique used to model the relationship between a response variable and one or more predictor variables. Unlike traditional regression models that estimate the mean of the response variable given the predictor variables, quantile regression estimates the conditional quantiles of the response variable.</p><p>An equal probability portion of a distribution is represented by a quantile. When the median is the 50th percentile, for instance, 50% of the distribution’s values fall below the median and 50% fall above it. We can estimate any conditional quantile of the response variable in quantile regression, not only the median.</p><p>Quantile regression’s primary benefit is that it enables us to model the relationship between the predictor variables across different parts of the distribution of the response variable. This can be useful when the relationship between the predictor variables and the response variable is not constant across the distribution, for example, when the relationship is stronger in the tails of the distribution.</p><p>Quantile regression can be a good choice if the data violate some of the key assumptions in ordinary least square regression (OLS): domesticity and normality. It is also robust to outliers or influential data points.</p><p>Without spending more time, I will proceed directly to the codes. I need few libraries and I will use the life_expectancy data set. I will use <em>quantreg</em> package to do the models(life expactancy as a function of income) and <em>plotly</em> to visualize the coefficients in 3D.</p><pre>library(pacman)<br>p_load(dplyr,janitor, ggplot2, quantreg,sjPlot, plotly)</pre><h3>Read Datasets</h3><pre>life_exp  &lt;- read.csv(&quot;life_expectancy.csv&quot;, na.strings = &quot;&quot;)<br>head(life_exp)</pre><pre>Country Year     Status Life.expectancy Adult.Mortality<br>1 Afghanistan 2015 Developing            65.0             263<br>2 Afghanistan 2014 Developing            59.9             271<br>3 Afghanistan 2013 Developing            59.9             268<br>4 Afghanistan 2012 Developing            59.5             272<br>5 Afghanistan 2011 Developing            59.2             275<br>6 Afghanistan 2010 Developing            58.8             279<br>  infant.deaths Alcohol percentage.expenditure Hepatitis.B Measles<br>1            62    0.01              71.279624          65    1154<br>2            64    0.01              73.523582          62     492<br>3            66    0.01              73.219243          64     430<br>4            69    0.01              78.184215          67    2787<br>5            71    0.01               7.097109          68    3013<br>6            74    0.01              79.679367          66    1989<br>   BMI under.five.deaths Polio Total.expenditure Diphtheria HIV.AIDS<br>1 19.1                83     6              8.16         65      0.1<br>2 18.6                86    58              8.18         62      0.1<br>3 18.1                89    62              8.13         64      0.1<br>4 17.6                93    67              8.52         67      0.1<br>5 17.2                97    68              7.87         68      0.1<br>6 16.7               102    66              9.20         66      0.1<br>        GDP Population thinness..1.19.years thinness.5.9.years<br>1 584.25921   33736494                 17.2               17.3<br>2 612.69651     327582                 17.5               17.5<br>3 631.74498   31731688                 17.7               17.7<br>4 669.95900    3696958                 17.9               18.0<br>5  63.53723    2978599                 18.2               18.2<br>6 553.32894    2883167                 18.4               18.4<br>  Income.composition.of.resources Schooling<br>1                           0.479      10.1<br>2                           0.476      10.0<br>3                           0.470       9.9<br>4                           0.463       9.8<br>5                           0.454       9.5<br>6                           0.448       9.2</pre><p>I will now do some data cleaning. The variable names are a bit tedious and to avoid using the backticks. I will simply clean up the column names using the <em>janitor</em> packages very useful <em>clean_names()</em> function</p><pre>life_expe_data  &lt;- clean_names(life_exp)<br>names(life_expe_data)</pre><pre>[1] &quot;country&quot;                        <br> [2] &quot;year&quot;                           <br> [3] &quot;status&quot;                         <br> [4] &quot;life_expectancy&quot;                <br> [5] &quot;adult_mortality&quot;                <br> [6] &quot;infant_deaths&quot;                  <br> [7] &quot;alcohol&quot;                        <br> [8] &quot;percentage_expenditure&quot;         <br> [9] &quot;hepatitis_b&quot;                    <br>[10] &quot;measles&quot;                        <br>[11] &quot;bmi&quot;                            <br>[12] &quot;under_five_deaths&quot;              <br>[13] &quot;polio&quot;                          <br>[14] &quot;total_expenditure&quot;              <br>[15] &quot;diphtheria&quot;                     <br>[16] &quot;hiv_aids&quot;                       <br>[17] &quot;gdp&quot;                            <br>[18] &quot;population&quot;                     <br>[19] &quot;thinness_1_19_years&quot;            <br>[20] &quot;thinness_5_9_years&quot;             <br>[21] &quot;income_composition_of_resources&quot;<br>[22] &quot;schooling&quot;</pre><p>Now the variable names are clean, we can do the rest of the coding as follows.I now remove the missing values. You can do better for your data by using imputation techniques to deal with missing values. But that is not my goal here today. Perhaps, I may do a blog or a YouTube video in the future. I just need you to demand for it or encourage me to do it.</p><pre>life_exp_narm  &lt;- life_expe_data[complete.cases(life_expe_data),]<br>dim(life_exp_narm)</pre><pre>[1] 1649   22</pre><pre>life_exp_narm &lt;- life_exp_narm |&gt; <br>  filter(income_composition_of_resources&gt;0) #let&#39;s remove all with income index around 0.</pre><p>We have about 22 variables and 1649 observations. Not bad for modelling! Since, <em>income_composition_of_resources</em> is a really long and boring variable name, I am changing it.</p><pre>names(life_exp_narm)[names(life_exp_narm) == &quot;income_composition_of_resources&quot;] &lt;- &quot;income_index&quot;</pre><pre>summary(life_exp_narm$income_index)</pre><pre>Min. 1st Qu.  Median    Mean 3rd Qu.    Max. <br> 0.2790  0.5290  0.6770  0.6505  0.7540  0.9360</pre><pre>sd(life_exp_narm$income_index)</pre><pre>[1] 0.1490056</pre><pre>summary(life_exp_narm$life_expectancy)</pre><pre>Min. 1st Qu.  Median    Mean 3rd Qu.    Max. <br>  44.00   64.60   71.80   69.39   75.00   89.00</pre><pre>sd(life_exp_narm$life_expectancy)</pre><pre>[1] 8.876531</pre><p>You can see that our main predictor variable has a mean 0.65 and SD of 0.149. It maybe a good idea to take a look at it by visualizing it. And the mean life expectancy was 69.4(SD=8.88)</p><pre>ggplot(life_exp_narm, aes(x=income_index, <br>                          y=life_expectancy, col=status)) + geom_point() +<br>geom_smooth(method = &quot;lm&quot;, col=&quot;blue&quot;) +<br>  xlab(&quot;Income index&quot;) + ylab(&quot;Life expectancy&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lQnaB2MfjiG7iHuB.png" /></figure><h3>Qauntile regression</h3><p>Before doing the quantile regression. It might be a good idea to take a look at the visualization by setting different tau values in abline of the base r plot showing the relationship between life_expectancy and income_index. The OLS regression is do the regression from the mean while the quantil regression n quantile regression, we can estimate any conditional quantile of the response variable, not just the mean but could be the medeian (50%), 90%, 75% or anywhere until 99%.If this is not clear, I highly recommended watching the video I dropped earlier. Let’s now visualize the mean and the median ablines</p><pre>plot(life_expectancy  ~ income_index, data = life_exp_narm) <br>abline(lm(life_expectancy  ~ income_index, data = life_exp_narm), col=&quot;blue&quot;, lwd = 3)<br>abline(rq(life_expectancy  ~ income_index, tau=0.5, data = life_exp_narm), col=&quot;red&quot;,  lwd = 4) # Notcie the tau=0.5,</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tpZ11ZSIPqFOpTG9.png" /></figure><p>You can see the plot blue line is the OLS regression line but the red line is if we model the regression using the median. If you have to run only two models and choose the model that best fits the data, you have to choose by AIC or using loss function(eg. the model with minimum mean squared error or mean absolute error, etc will be the best fit). NB: choosing the right model is not my goal here.</p><p>Now let’s add 10th and 90th percentiles from the above vizualization and evaluate which line looks better fit for the relationship between the two variables.</p><pre>plot(life_expectancy  ~ income_index, data = life_exp_narm) <br>abline(lm(life_expectancy  ~ income_index, data = life_exp_narm), col=&quot;blue&quot;, lwd = 3)<br>abline(rq(life_expectancy  ~ income_index, tau=0.5, data = life_exp_narm), col=&quot;red&quot;,  lwd = 4)<br>abline(rq(life_expectancy  ~ income_index, tau=0.1, data = life_exp_narm), col=&quot;black&quot;,  lwd = 5)<br>abline(rq(life_expectancy  ~ income_index, tau=0.90, data = life_exp_narm), col=&quot;turquoise4&quot;,  lwd = 6)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*G99bXoP57Rp_yCoQ.png" /></figure><p>We can actually visualize multiple quantreg models and see it compared to the OLS model.</p><pre>ggplot(life_exp_narm, aes(income_index, life_expectancy))+<br>    geom_point()+<br>    geom_smooth(method = lm, se = F, color = &quot;darkturquoise&quot;)+ #linear model<br>    geom_quantile(color = &quot;red&quot;, quantiles = 0.5)+<br>    geom_quantile(color = &quot;black&quot;, alpha = 0.2, #Quantreg based on median<br>                  quantiles = seq(.05, .95, by = 0.05)) #multiple models from the 5th percentile to 95th percentile</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qti4c5Yc1KH18_yQ.png" /></figure><p>Let’s now run four different models at the mean(OLS), and quantile regressions at the median, 10th percentile and 95th percentiles. Notice the tau values. I also added one more variable.</p><pre>ols &lt;-  rq(life_expectancy~income_index+schooling, data = life_exp_narm) #Similar to lm()<br>quant_reg_med  &lt;- rq(life_expectancy~income_index+schooling,tau = 0.5, data = life_exp_narm)<br>quant_reg_first  &lt;- rq(life_expectancy~income_index+schooling,tau = 0.1, data = life_exp_narm)<br>quant_reg_last  &lt;- rq(life_expectancy~income_index+schooling,tau = 0.95, data = life_exp_narm)</pre><pre>summary(ols)</pre><pre>Call: rq(formula = life_expectancy ~ income_index + schooling, data = life_exp_narm)</pre><pre>tau: [1] 0.5</pre><pre>Coefficients:<br>             Value    Std. Error t value  Pr(&gt;|t|)<br>(Intercept)  38.59204  0.56239   68.62125  0.00000<br>income_index 62.04691  1.98135   31.31544  0.00000<br>schooling    -0.75195  0.10388   -7.23903  0.00000</pre><pre>summary(quant_reg_med)</pre><pre>Call: rq(formula = life_expectancy ~ income_index + schooling, tau = 0.5, <br>    data = life_exp_narm)</pre><pre>tau: [1] 0.5</pre><pre>Coefficients:<br>             Value    Std. Error t value  Pr(&gt;|t|)<br>(Intercept)  38.59204  0.56239   68.62125  0.00000<br>income_index 62.04691  1.98135   31.31544  0.00000<br>schooling    -0.75195  0.10388   -7.23903  0.00000</pre><pre>summary(quant_reg_first)</pre><pre>Call: rq(formula = life_expectancy ~ income_index + schooling, tau = 0.1, <br>    data = life_exp_narm)</pre><pre>tau: [1] 0.1</pre><pre>Coefficients:<br>             Value    Std. Error t value  Pr(&gt;|t|)<br>(Intercept)  25.92063  1.81747   14.26195  0.00000<br>income_index 84.00142  5.34145   15.72633  0.00000<br>schooling    -1.34938  0.22578   -5.97661  0.00000</pre><pre>summary(quant_reg_last)</pre><pre>Call: rq(formula = life_expectancy ~ income_index + schooling, tau = 0.95, <br>    data = life_exp_narm)</pre><pre>tau: [1] 0.95</pre><pre>Coefficients:<br>             Value     Std. Error t value   Pr(&gt;|t|) <br>(Intercept)   46.56308   0.40214  115.78932   0.00000<br>income_index  57.37912   2.25777   25.41402   0.00000<br>schooling     -0.69824   0.10643   -6.56032   0.00000</pre><p>Let’s have a closer look of the median model relative to the lm.</p><pre># Plot data points and regression models<br>ggplot(life_exp_narm, aes(income_index, life_expectancy)) +<br>  geom_point() +<br>  geom_smooth(method = lm, se = FALSE, color = &quot;red&quot;, size = 0.5) + # linear model<br>  geom_quantile(color = &quot;darkturquoise&quot;, quantiles = 0.5, size=2) + # median quantile regression model with tau = 0.5<br>    geom_quantile(color = &quot;black&quot;, quantiles = 0.1, size=0.5) + #quantreg based on the 10th percentile<br>      geom_quantile(color = &quot;yellow&quot;, quantiles = 0.75, size= 0.5) + #quantreg based on the 10th percentile<br>  geom_segment(aes(x = income_index, y = life_expectancy, xend = income_index, yend = predict(quant_reg_med, newdata = life_exp_narm)), <br>               color = &quot;darkgray&quot;, size = 0.1) + # distance line based on median quantile regression model<br>  labs(title = &quot; Life Expectancy~Income Index&quot;, y = &quot;Life Expectancy&quot;, x = &quot;Income Index&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Syv30_ygo2bBQaUl.png" /></figure><p>We can plot the coefficients of the four different models we modeled earlier and compare them.</p><pre>plot_models(ols, quant_reg_med, quant_reg_first, quant_reg_last,<br>           show.values = TRUE,<br>           m.labels = c(&quot;OLS&quot;, &quot;Median&quot;, &quot;10th percentile&quot;,<br>                       &quot;95th percentile&quot;,<br>                       legend.title = &quot;Model&quot;)<br>           )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*b7OAder77joDftEs.png" /></figure><p>You can see the OLS(based one mean) and quanitile regression based on the median are identical.But the one with 10th percentile and 95th percentile are different from the coefficients of the OLS.</p><p>For effectively modeling numerous quantreg models, you may do somthing like the following.</p><pre>taus&lt;-seq(from = .05, to = .95, by = 0.05) #Taus ranging from 0.05 to 0.95 with a step value of 0.05<br>quant_all  &lt;- rq(life_expectancy~income_index,tau = taus, <br>                 data = life_exp_narm)</pre><pre>names(quant_all) #To access the cntents of our model</pre><pre>[1] &quot;coefficients&quot;  &quot;x&quot;             &quot;y&quot;             &quot;residuals&quot;    <br> [5] &quot;dual&quot;          &quot;fitted.values&quot; &quot;formula&quot;       &quot;terms&quot;        <br> [9] &quot;xlevels&quot;       &quot;call&quot;          &quot;tau&quot;           &quot;rho&quot;          <br>[13] &quot;method&quot;        &quot;model&quot;</pre><pre>quant_all$tau #To see the taus</pre><pre>[1] 0.05 0.10 0.15 0.20 0.25 0.30 0.35 0.40 0.45 0.50 0.55 0.60 0.65<br>[14] 0.70 0.75 0.80 0.85 0.90 0.95</pre><p>With that we have got several models. But how we access a specific model for example when tau=0.8 or tau=0.1?</p><pre>summary(quant_all)[which(taus == 0.8)]</pre><pre>Call: rq(formula = life_expectancy ~ income_index, tau = taus, data = life_exp_narm)</pre><pre>tau: [1] 0.8</pre><pre>Coefficients:<br>             Value    Std. Error t value  Pr(&gt;|t|)<br>(Intercept)  44.77157  0.62620   71.49715  0.00000<br>income_index 42.89216  0.79348   54.05567  0.00000</pre><pre>summary(quant_all)[which(taus == 0.1)]</pre><pre>Call: rq(formula = life_expectancy ~ income_index, tau = taus, data = life_exp_narm)</pre><pre>tau: [1] 0.1</pre><pre>Coefficients:<br>             Value    Std. Error t value  Pr(&gt;|t|)<br>(Intercept)  20.52315  1.70906   12.00844  0.00000<br>income_index 65.74074  2.18924   30.02897  0.00000</pre><p>If we want to compare the AIC values of these models, as usual we can use AIC()</p><pre>aic_df &lt;- data.frame(AIC = AIC(quant_all), model = paste(&quot;tau =&quot;,taus))<br>head(aic_df)</pre><pre>AIC      model<br>1 10945.777 tau = 0.05<br>2 10550.411  tau = 0.1<br>3 10230.887 tau = 0.15<br>4  9978.270  tau = 0.2<br>5  9771.004 tau = 0.25<br>6  9618.262  tau = 0.3</pre><pre>ggplot(aic_df, aes(x = model, y = AIC)) +<br>  geom_bar(stat = &quot;identity&quot;, fill = &quot;steelblue&quot;) +<br>  labs(title = &quot;AIC values for different tau values&quot;,<br>       x = &quot;Quantile regression models with different Tau values&quot;,<br>       y = &quot;Akaike Information Criterion&quot;) +<br>    theme(axis.text.x = element_text(angle = 90, hjust = 1))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*e4Kn2KugMiLg8d4Q.png" /></figure><p>It seems the model around the median point is better fit. In general, we ought to pick the model with the lowest AIC score. AIC (Akaike Information Criterion) is a metric used to assess a statistical model’s suitability for a particular set of data. It is based on the model’s complexity as well as its goodness of fit. The model is thought to be better the lower the AIC value.</p><p>However, it’s crucial to remember that the AIC should not be the only factor considered when choosing a model. When choosing a model, it is important to take into account a number of additional elements, including interpretability, applicability, and theoretical relevance. It’s also possible that none of the models have an AIC that is noticeably superior to the others, in which case other factors might be more crucial in selecting a model.</p><h3>How about if we want to access the coefficients?</h3><pre>QR.coef &lt;- coef(quant_all)</pre><p>Or in a more complicated way like the following</p><pre>lprq &lt;-  function(x, y, h, m=19 , tau=.5)<br>  {<br>    xx &lt;- seq(min(x),max(x),length=m)<br>    fv &lt;- xx<br>    dv &lt;- xx<br>    for(i in 1:length(xx)) {<br>      z &lt;- x - xx[i]<br>      wx &lt;- dnorm(z/h)<br>      r &lt;- rq(y~z, weights=wx, tau=tau, ci=FALSE)<br>      fv[i] &lt;- r$coef[1.] <br>      dv[i] &lt;- r$coef[2.]  <br>    }<br>    data.frame(dv = dv)<br>}</pre><pre>#Create a matrix to save the QQR estimates<br>taus&lt;-seq(from = .05, to = .95, by = 0.05)</pre><pre>QQR.coef &lt;- as.data.frame(matrix(0, ncol = 19, nrow = 19))</pre><pre># Run QQR in a loop and save estimates in matrix &quot;QQR.coef&quot;<br>#Note: 0.05 in below loop is the bandwidth that can be adjusted</pre><pre>o &lt;-life_exp_narm$life_expectancy<br>p &lt;-life_exp_narm$income_index</pre><pre>for (i in 1:19){<br>  x&lt;-lprq(o, p,0.05,tau=taus[i])<br>  QQR.coef[,i]&lt;-x<br>}</pre><p>Let’s now save all coefficients in a matrix</p><pre>beta &lt;- as.matrix(QQR.coef)</pre><h3>Vizualize</h3><pre>p &lt;- plot_ly( z = ~beta, x = ~taus, y = ~taus, opacity = 0.6) %&gt;%<br>  add_markers()</pre><pre>p %&gt;% add_surface(z = ~beta, x = ~taus, y = ~taus, showscale = FALSE) %&gt;%<br>  layout(showlegend = FALSE)<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ADEwTM_pojm1vfVYJm_xjg.gif" /></figure><h3>Quantile process plot</h3><pre>summary(quant_all) |&gt; plot(&quot;income_index&quot;) #Let&#39;s ignore the intercept</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Y_Ywxm7qry6Sv44u.png" /></figure><p>The summary(quant_all) |&gt; plot(“income_index”) command generates a Quantile Process Plot for the variable income_index. A quantile process plot is a graphical tool to assess the relationship between the response variable (in our case, life_expectancy) and the predictor variable (income_index) across different quantiles of the response distribution. The x-axis represents the predictor variable, and the y-axis represents the quantiles of the response variable. The plot shows a line for each quantile of interest (0.05, 0.1, 0.15, …, 0.95), indicating the estimated relationship between income_index and the corresponding quantile of life_expectancy. The shaded area is for quantile regression and its confidence intervals.The slope of each line represents the estimated effect of income_index on the given quantile of life_expectancy. The solid and dashed red lines show the linear model and its lower and upper bound confidence intervals, respectively. In the plot, we can see only a very small region(from around 0.25 to 0.4) overlaps with the linear model. The large portion of the plot when the income index is larger than 0.4 or when it is lower than 0.2 is not overlapping indicating the difference between the quantreg approach and the OLS modeling approach.</p><p>In addition, we can see curvatures or non-linearity in the lines, which may indicate that the relationship between the variables is more complex than a simple linear one. Hence, a more complex model may be necessary to capture the full range of the relationship between the two variables.</p><p>That is all for today. Again I highly recommend watching the video and reading quantreg package functions. I hope you like it. See you in the next post.</p><h3>Contact</h3><p>Please mention <a href="https://twitter.com/RPy_DataScience">@RPy_DataScience</a> if you tweet this post.<br>I regularly post R and Python videos on my YouTube channel. Consider subscribing. <a href="https://www.youtube.com/channel/UCpHd6O1Yqz4YgcYUBfyRqKg">https://www.youtube.com/channel/UCpHd6O1Yqz4YgcYUBfyRqKg</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2eec72c132b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Animating bar graphs]]></title>
            <link>https://drkebede.medium.com/animating-bar-graphs-5bfc5eda87dc?source=rss-7dc19c3314ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/5bfc5eda87dc</guid>
            <category><![CDATA[ggplot2]]></category>
            <category><![CDATA[dataviz]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[gganimate]]></category>
            <dc:creator><![CDATA[Mihiretu M Kebede (PhD)]]></dc:creator>
            <pubDate>Mon, 21 Jun 2021 10:36:51 GMT</pubDate>
            <atom:updated>2021-06-21T10:36:51.685Z</atom:updated>
            <content:encoded><![CDATA[<p>In this short blog post, I will demonstrate a simple bar chart to an animated bar chart. The data is from my daily footstep counts measured by one of the daily fitness tracker apps in iPhone.</p><pre>#Set working directory<br><br>library(readxl) #for reading my excel data<br>library(ggplot2)#for awesome data vizualization <br>library(gganimate) #for animating ggplot2 plots</pre><pre>mystepcount &lt;- read_excel(&quot;mystepcount.xlsx&quot;)<br><br>str(mystepcount)</pre><pre>tibble [8 x 4] (S3: tbl_df/tbl/data.frame)<br> $ Date       : chr [1:8] &quot;Sept_14&quot; &quot;Sept_15&quot; &quot;Sept_16&quot; &quot;Sept_17&quot; ...<br> $ September  : num [1:8] 14 15 16 17 18 19 20 21<br> $ Steps      : num [1:8] 1907 18767 10438 23128 28300 ...<br> $ Killometres: num [1:8] 1.1 12.8 7.4 17.1 19.1 12.9 13.7 4.9</pre><pre>library(ggplot2)<br>library(gganimate)<br>library(scales)<br>theme_set(theme_bw())<br><br>mystepcount$September &lt;- as.character(mystepcount$September)</pre><pre>plot &lt;- ggplot(mystepcount, aes(x=September,y=Steps)) + <br>  geom_bar(fill=&quot;#004C99&quot;, stat=&quot;identity&quot;, width=1,  position=position_dodge()) + <br>    geom_hline(yintercept = 10000, col=&quot;black&quot;, size=1)</pre><pre>plot<br># The simple ggplot looks like the following</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8b-eUx5FHHT40DlH.png" /></figure><pre># I will now few lines of code to make the animation possible. </pre><pre>plot &lt;- plot + <br>    geom_hline(yintercept = 10000, col=&quot;black&quot;, size=1) +<br>  transition_states(September, wrap = FALSE) +<br>  shadow_mark() +<br>  enter_grow() +<br>  enter_fade() + <br>  theme(axis.text = element_text(size=16),<br>        axis.title = element_text(size=16, face=&quot;bold&quot;)) + <br>  xlab(&quot;September&quot;) +  <br>  scale_y_discrete(name=&quot;Step counts&quot;, limits=c(5000,10000, 15000, 20000, 25000, 30000)) +<br>  theme(axis.line = element_line(colour = &quot;black&quot;),<br>          panel.border = element_blank())</pre><pre># Finally use animate() function from the gganimate package </pre><pre>animate(plot,duration = .001)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/0*F_NezKJZGRD4luMt.gif" /></figure><p>Thank you for reading this post. I hope you find this helpful. For more, subscribe to my <a href="https://www.youtube.com/channel/UCpHd6O1Yqz4YgcYUBfyRqKg">YouTube channel</a> and follow me on Twitter @<a href="https://twitter.com/RPy_DataScience">RPy_DataScience</a>.You can also follow me by liking <a href="https://web.facebook.com/R_Py-Data-Science-105325938441990/news_feed">R_Py Data Science</a> Facebook page.</p><h3>Contact</h3><p>Please mention @<a href="https://twitter.com/RPy_DataScience">RPy_DataScience</a> if you tweet this post.</p><p><a href="https://www.mihiretukebede.com/posts/2021-06-07-scraping-individual-participant-data-from-scatter-plots/">https://www.mihiretukebede.com/posts/2021-06-07-scraping-individual-participant-data-from-scatter-plots/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5bfc5eda87dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Applying text analyses methods on 382 COVID19 journal articles]]></title>
            <link>https://drkebede.medium.com/applying-text-analyses-methods-on-382-covid19-journal-articles-c86ecf32b5b9?source=rss-7dc19c3314ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/c86ecf32b5b9</guid>
            <category><![CDATA[bibliometrics]]></category>
            <category><![CDATA[text-mining]]></category>
            <category><![CDATA[language-model]]></category>
            <category><![CDATA[text-analysis]]></category>
            <category><![CDATA[covid19]]></category>
            <dc:creator><![CDATA[Mihiretu M Kebede (PhD)]]></dc:creator>
            <pubDate>Mon, 14 Jun 2021 08:00:05 GMT</pubDate>
            <atom:updated>2021-06-14T08:01:33.230Z</atom:updated>
            <content:encoded><![CDATA[<h3>Load necessary packages</h3><p>For this analysis, I need the following packages</p><pre>library(dplyr) #for data management<br>library(ggplot2) #for plotting<br>library(tidytext) #for text mining<br>library(bib2df) #for converting bib file to data frame<br>library(wordcloud) #for plotting most frequent words</pre><h3>Data</h3><p>Let’s import our bibliographic data using bib2df package as described in my previous <a href="http://www.mihiretukebede.com/posts/2020-08-03-2020-08-03-covid19/">blog post</a></p><pre>library(bib2df)<br>covid19 &lt;- bib2df(&quot;covid19.bib&quot;)</pre><p>As usual, let’s have a quick glimpse of our data.</p><pre>glimpse(covid19)</pre><pre>Rows: 601<br>Columns: 32<br>$ CATEGORY     &lt;chr&gt; &quot;MISC&quot;, &quot;ARTICLE&quot;, &quot;ARTICLE&quot;, &quot;ARTICLE&quot;, &quot;MI...<br>$ BIBTEXKEY    &lt;chr&gt; &quot;Gelzinis2020&quot;, &quot;Coccia2020&quot;, &quot;Ataguba2020&quot;,...<br>$ ADDRESS      &lt;chr&gt; NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, ...<br>$ ANNOTE       &lt;chr&gt; NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, ...<br>$ AUTHOR       &lt;list&gt; [&quot;Gelzinis, Theresa A&quot;, &quot;Coccia, Mario&quot;, &lt;&quot;...<br>$ BOOKTITLE    &lt;chr&gt; &quot;Journal of cardiothoracic and vascular anes...<br>$ CHAPTER      &lt;chr&gt; NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, ...<br>$ CROSSREF     &lt;chr&gt; NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, ...<br>$ EDITION      &lt;chr&gt; NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, ...<br>$ EDITOR       &lt;list&gt; [NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA...<br>$ HOWPUBLISHED &lt;chr&gt; NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, ...<br>$ INSTITUTION  &lt;chr&gt; NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, ...<br>$ JOURNAL      &lt;chr&gt; NA, &quot;The Science of the total environment&quot;, ...<br>$ KEY          &lt;chr&gt; NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, ...<br>$ MONTH        &lt;chr&gt; &quot;sep&quot;, &quot;aug&quot;, &quot;dec&quot;, &quot;sep&quot;, &quot;dec&quot;, &quot;nov&quot;, &quot;s...<br>$ NOTE         &lt;chr&gt; NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, ...<br>$ NUMBER       &lt;chr&gt; &quot;9&quot;, NA, &quot;1&quot;, NA, &quot;1&quot;, NA, NA, &quot;1&quot;, NA, NA, ...<br>$ ORGANIZATION &lt;chr&gt; NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, ...<br>$ PAGES        &lt;chr&gt; &quot;2328--2330&quot;, &quot;138474&quot;, &quot;1788263&quot;, &quot;312--321...<br>$ PUBLISHER    &lt;chr&gt; NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, ...<br>$ SCHOOL       &lt;chr&gt; NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, ...<br>$ SERIES       &lt;chr&gt; NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, ...<br>$ TITLE        &lt;chr&gt; &quot;Thoracic Anesthesia in the Coronavirus Dise...<br>$ TYPE         &lt;chr&gt; NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, ...<br>$ VOLUME       &lt;chr&gt; &quot;34&quot;, &quot;729&quot;, &quot;13&quot;, &quot;117&quot;, &quot;9&quot;, &quot;110&quot;, &quot;83&quot;, ...<br>$ YEAR         &lt;dbl&gt; 2020, 2020, 2020, 2020, 2020, 2020, 2020, 20...<br>$ DOI          &lt;chr&gt; &quot;10.1053/j.jvca.2020.05.008&quot;, &quot;10.1016/j.sci...<br>$ ISSN         &lt;chr&gt; &quot;1532-8422 (Electronic)&quot;, &quot;1879-1026 (Electr...<br>$ LANGUAGE     &lt;chr&gt; &quot;eng&quot;, &quot;eng&quot;, &quot;eng&quot;, &quot;eng&quot;, &quot;eng&quot;, &quot;eng&quot;, &quot;e...<br>$ PMID         &lt;chr&gt; &quot;32406428&quot;, &quot;32498152&quot;, &quot;32657669&quot;, &quot;3254687...<br>$ ABSTRACT     &lt;chr&gt; NA, &quot;This study has two goals. The first is ...<br>$ KEYWORDS     &lt;chr&gt; NA, &quot;Air Pollutants,Air Pollution,Betacorona...</pre><pre>dim(covid19) #601 documents and 32 variables</pre><pre>[1] 601  32</pre><p>Once you read the file, it will be saved in our environment as a data frame and we can do our analysis. As usual, the first part of the analysis is doing some descriptives and visualizing the data. We will then move to tokenization steps. <strong><em>Token</em></strong> is a meaningful unit of a <strong><em>text</em></strong>. This meaningful unit is represented by a word or a term. It is the unit that text analysts are interested in doing their analysis. The process of breaking down a text into a set of tokens is known as <strong>tokenization</strong>. For example</p><p>Text: “COVID19 is the biggest global health crisis of the modern world”. In this text, the tokens are each word. In the tokenization process, each of these words is written in separate columns(variable) as follows.</p><p>In the tokenization process, the text documents are changed to tokens and each token is counted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*spejlRUlXCxAUoChRntbog.png" /></figure><p>TextCOVID19isthebiggestglobalhealthcrisisofthemodernworldCOVID19 is the biggest global health crisis of the modern world11111111111</p><p>In the tokenization process, the text documents are changed to tokens and each token is counted. Notice “the” is mentioned twice. So, we can count it and reshuffle our table as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*jlQRLQvSXh1LNLUWSxMf2g.png" /></figure><p>TextCOVID19isthebiggestglobalhealthcrisisofmodernworldCOVID19 is the biggest global health crisis of the modern world1121111111</p><p>The next thing after tokenization is removing irrelevant words. These are words that don’t give much information to the concept of the document other than making the grammatical structure of the document. The stp_words data has about 1150 irrelevant words. These words can be easily removed using the dyplyr ant_join function.</p><p>We have enough of theory. Let’s move to the more technical things. As we did in the previous blog, we will only need journal articles having no missing data on their abstract variable.</p><pre>library(dplyr)<br>covid19new &lt;- covid19 %&gt;%<br>  filter(!is.na(ABSTRACT)) #remove all records with missing abstracts</pre><pre>table(covid19new$CATEGORY) #382 are journal articles with no missing abstract</pre><pre>ARTICLE    MISC <br>    382      60</pre><pre># Filter journal articles having  abstracts <br>covid19new &lt;- covid19new %&gt;% <br>  filter(CATEGORY==&quot;ARTICLE&quot;) <br>#Check <br>table(covid19new$CATEGORY) #382 journal articles</pre><pre>ARTICLE <br>    382</pre><h3>Tokenization</h3><pre># select few variables from our data set<br>data &lt;- covid19new %&gt;% <br>  select(&quot;TITLE&quot;, &quot;ABSTRACT&quot;, &quot;KEYWORDS&quot;, &quot;AUTHOR&quot;)</pre><p>To start with the tokenization process, we will load stop_words data. We can also add our own stop words. In text mining, words on both sides of extreme frequency are no relevant. These words can be removed by creating a customized list of stop_words. Since we are doing our text analysis on journal articles, words that are obviously common in each of the abstracts can be removed. Structured abstracts usually contain “Introduction” or “background”, “Methods”, “Results”, and “conclusions”. These and other words can be removed. The custom stop words can also include “covid”, since all of them are about “covid”. There is also a way to remove numbers from our corpus. For now, we will not remove all numbers.</p><pre>data(stopwords)<br>custom_stop_words &lt;- bind_rows(tibble(word=c(&quot;covid&quot;, &quot;covid19&quot;,&quot;covid-19&quot;, &quot;sars&quot;, &quot;sars&quot;, &quot;cov&quot;, &quot;background&quot;, &quot;introduction&quot;,&quot;aims&quot;, &quot;objectives&quot;, &quot;materials&quot;, &quot;methods&quot;, &quot;results&quot;, &quot;conclusions&quot;,&quot;textless&quot;, &quot;0&quot;, &quot;1&quot;,&quot;2&quot;, &quot;3&quot;, &quot;4&quot;, &quot;5&quot;, &quot;6&quot;, &quot;7&quot;, &quot;8&quot;, &quot;9&quot;,&quot;19&quot;, &quot;2019&quot;, &quot;2020&quot;, &quot;95&quot;),<br>                                      lexicon = c(&quot;custom&quot;)),<br>                               stop_words)<br></pre><pre>tidy_covid_data &lt;- data %&gt;% <br>  unnest_tokens(input=ABSTRACT, output=word) %&gt;% <br>  anti_join(stop_words) %&gt;% <br>  anti_join(custom_stop_words)</pre><pre>dim(tidy_covid_data) # 40669 tokens, 4 variables</pre><pre>[1] 40647     4</pre><h3>Count the number of words and visualize it using bar chart.</h3><pre>tidy_covid_data %&gt;% <br>  count(word, sort=T) %&gt;% <br>   filter(n&gt;100) %&gt;% <br>   mutate(word=reorder(word, n)) %&gt;% <br>   ggplot(aes(x=word, y=n)) + <br>   geom_col(fill=&quot;#619CFF&quot;) + coord_flip()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mvaWzs3jERtHyGQ2.png" /></figure><h3>Visualize most frequent words using wordcloud</h3><pre>library(wordcloud)<br>pal &lt;- brewer.pal(8, &quot;Dark2&quot;)<br>tidy_covid_data %&gt;% <br>  count(word) %&gt;% <br>  with(wordcloud(word, n, max.words=700, colors = pal))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pF2dqECRhoA2I5NW.png" /></figure><h3>Relationship between words</h3><p>The relationship between words can be visualized in a network graph after tokenizing using n-grams. n-grams are breaking a text in two-, three or n-number of word tokens.</p><p>For now, we will only see bigrams(two-word tokens). Two-word tokens can be represented as follows</p><ol><li>text1: “How dangerous is COVID19?”</li></ol><p>2. text 2: “How dangerous is COVID19 pandemic.?”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*BV7VO_Q7ZEtowq5HIJWkfA.png" /></figure><p>As we did previously, lets do the tokenization once again. This time using bigrams.</p><pre>covid_bigram &lt;- data[, c(1,2,3)] %&gt;% #selct only titles, abstracts and keywords column of the data. Title is saved<br>  unnest_tokens(output=bigram, <br>                input=ABSTRACT,<br>                token=&quot;ngrams&quot;, n=2)</pre><pre>dim(covid_bigram) # 79404 bigrams, 3 variables</pre><pre>[1] 79404     3</pre><p>Let’s see the most frequent bigrams. Notice the irrelevant words.</p><pre>head(<br>  covid_bigram %&gt;%<br>  count(bigram, sort = TRUE)<br>)</pre><pre># A tibble: 6 x 2<br>  bigram       n<br>  &lt;chr&gt;    &lt;int&gt;<br>1 covid 19   989<br>2 of the     571<br>3 sars cov   443<br>4 cov 2      401<br>5 in the     384<br>6 of covid   212</pre><h3>Remove useless words</h3><pre>library(tidyr)</pre><pre>covid_bigrams_separated &lt;- covid_bigram %&gt;%<br>  separate(bigram, c(&quot;word1&quot;, &quot;word2&quot;), sep = &quot; &quot;)</pre><pre>covd_bigrams_filtered &lt;- covid_bigrams_separated %&gt;%<br>  filter(!word1 %in% stop_words$word) %&gt;%<br>  filter(!word2 %in% stop_words$word) %&gt;% <br>  filter(!word1 %in% custom_stop_words$word) %&gt;%<br>  filter(!word2 %in% custom_stop_words$word)</pre><pre>dim(covd_bigrams_filtered) # 18981 bigrams, 4 variables</pre><pre>[1] 18963     4</pre><pre>covd_bigrams_filtered_counts &lt;- covd_bigrams_filtered %&gt;% <br>  count(word1, word2, sort = TRUE)</pre><pre>head(covd_bigrams_filtered_counts)</pre><pre># A tibble: 6 x 3<br>  word1       word2           n<br>  &lt;chr&gt;       &lt;chr&gt;       &lt;int&gt;<br>1 coronavirus disease        95<br>2 acute       respiratory    78<br>3 respiratory syndrome       75<br>4 severe      acute          68<br>5 syndrome    coronavirus    54<br>6 public      health         49</pre><p>As you can see from the dim( ) call, the tokenization process changed the abstract of the 382 documents to 41000 tokens. That means we have 382 observations and 41000 one-word columns. In the bigram tokenization, we have about 19000 bigrams for our 382 abstracts.</p><p>Now, let’s join the separated bigrams.</p><pre>covid_bigrams_united &lt;- covd_bigrams_filtered %&gt;%<br>  unite(bigram, word1, word2, sep = &quot; &quot;)</pre><pre>covd_bigrams_joined_counts &lt;- covid_bigrams_united %&gt;% <br>  count(bigram, sort = TRUE)</pre><pre>head(covd_bigrams_joined_counts)</pre><pre># A tibble: 6 x 2<br>  bigram                   n<br>  &lt;chr&gt;                &lt;int&gt;<br>1 coronavirus disease     95<br>2 acute respiratory       78<br>3 respiratory syndrome    75<br>4 severe acute            68<br>5 syndrome coronavirus    54<br>6 public health           49</pre><h3>Visualize bigrams</h3><h3>Word cloud</h3><pre>#Let&#39;s visualize 150 most common words<br>library(wordcloud)<br>pal &lt;- brewer.pal(8, &quot;Dark2&quot;)<br>covid_bigrams_united %&gt;% <br>  count(bigram) %&gt;% <br>  with(wordcloud(bigram, n, max.words=150, colors = pal))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EAPNe3-ZLuLCr1jT.png" /></figure><p>The word cloud above shows, “severe acute”, “wuhan china”, “air pollution”, “rt pcr”, “personal protective”, “cytokine storm” and “social distancing” as most common bigrams in the covid19 publications included in this analysis.</p><h3>Network graph</h3><pre>library(igraph)<br>library(ggplot2)<br>bigram_graph &lt;- covd_bigrams_filtered_counts %&gt;%<br>  filter(n &gt; 8) %&gt;% #words mentioned more than 8 timse<br>  graph_from_data_frame()</pre><pre>bigram_graph</pre><pre>IGRAPH 0e07d00 DN-- 103 70 -- <br>+ attr: name (v/c), n (e/n)<br>+ edges from 0e07d00 (vertex names):<br> [1] coronavirus-&gt;disease      acute      -&gt;respiratory <br> [3] respiratory-&gt;syndrome     severe     -&gt;acute       <br> [5] syndrome   -&gt;coronavirus  public     -&gt;health      <br> [7] health     -&gt;care         nâ         -&gt;â           <br> [9] mental     -&gt;health       air        -&gt;quality     <br>[11] â          -&gt;â            rt         -&gt;pcr         <br>[13] world      -&gt;health       health     -&gt;organization<br>[15] pm         -&gt;10           air        -&gt;pollution   <br>+ ... omitted several edges</pre><pre>library(ggraph)<br>set.seed(2017)</pre><pre>ggraph(bigram_graph, layout = &quot;fr&quot;) +<br>  geom_edge_link() +<br>  geom_node_point() +<br>  geom_node_text(aes(label = name), vjust = 1, hjust = 1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HEkZuT64llk52Umi.png" /></figure><p>Term frequency inverse document frequency (tf-idf) is a weighted numerical representation of how a certain word is important in a document. It is calculated using the following formula. tf_idf can be done for the one word columns. For now, let’s just do for bigrams instead.</p><p>tfidf(t,d,D)=tf(t,d)×idf(t,D)tfidf(t,d,D)=tf(t,d)×idf(t,D)</p><p>idf(t,D)=log| D |1+| {d∈D:t∈d} |idf(t,D)=log| D |1+| {d∈D:t∈d} |</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*Vz8LhfByHE0FiRphJCw0QQ.png" /></figure><p>Where t is the terms appearing in a document; d denotes each document; D denotes the collection of documents.</p><pre>covid_bigram_tf_idf &lt;- covid_bigrams_united %&gt;%<br>  count(TITLE, bigram) %&gt;%<br>  bind_tf_idf(bigram, TITLE, n) %&gt;%<br>  arrange(desc(tf_idf))</pre><pre>head(covid_bigram_tf_idf)</pre><pre># A tibble: 6 x 6<br>  TITLE                          bigram           n    tf   idf tf_idf<br>  &lt;chr&gt;                          &lt;chr&gt;        &lt;int&gt; &lt;dbl&gt; &lt;dbl&gt;  &lt;dbl&gt;<br>1 Arthroplasty during the COVID~ arthroplast~     1 0.5    5.95   2.97<br>2 Arthroplasty during the COVID~ safely navi~     1 0.5    5.95   2.97<br>3 COVID-19 Reveals Brugada Patt~ brugada pat~     3 0.375  5.95   2.23<br>4 Neutrophils and COVID-19: Not~ increase ef~     1 0.333  5.95   1.98<br>5 Neutrophils and COVID-19: Not~ pandemic ma~     1 0.333  5.25   1.75<br>6 COVID-19 Time Capsule 1: DATE~ time capsule     2 0.286  5.95   1.70</pre><pre>covid_bigram_tf_idf %&gt;%<br>  arrange(desc(tf_idf)) %&gt;%<br>  mutate(bigram = factor(bigram, levels = rev(unique(bigram)))) %&gt;% <br>  top_n(15) %&gt;% <br>  ggplot(aes(bigram, tf_idf)) +<br>  geom_col(show.legend = FALSE, fill=&quot;cyan4&quot;) +<br>  labs(x = NULL, y = &quot;tf-idf&quot;) +<br>  coord_flip()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iz1wGGXHR2DDp2NU.png" /></figure><p>The above <em>tf_idf</em> plot shows, “athroplasyty practice”, “safely navigate”, “brugada pattern”, etc were bigrams having the highest tf_idf values.</p><p>That is all for today.</p><p>Thank you for reading this post. I hope you find this helpful. For more explanations and data science tutorials, please subscribe to my <a href="https://www.youtube.com/channel/UCpHd6O1Yqz4YgcYUBfyRqKg">YouTube channel</a> or follow me on Twitter @<a href="https://twitter.com/RPy_DataScience">RPy_DataScience</a>.You can also follow me by liking <a href="https://web.facebook.com/R_Py-Data-Science-105325938441990/news_feed">R_Py Data Science</a> Facebook page.</p><h3>Contact</h3><p>Please mention @<a href="https://twitter.com/RPy_DataScience">RPy_DataScience</a> if you tweet this post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c86ecf32b5b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[XGboost, Naive Bayes and SVM Machine learning algorithms for facilitating title-abstract screening…]]></title>
            <link>https://drkebede.medium.com/xgboost-naive-bayes-and-svm-machine-learning-algorithms-for-facilitating-title-abstract-screening-3a7df05abed3?source=rss-7dc19c3314ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a7df05abed3</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[text-mining]]></category>
            <category><![CDATA[xgboost]]></category>
            <category><![CDATA[systematic-review]]></category>
            <category><![CDATA[support-vector-machine]]></category>
            <dc:creator><![CDATA[Mihiretu M Kebede (PhD)]]></dc:creator>
            <pubDate>Fri, 11 Jun 2021 08:09:18 GMT</pubDate>
            <atom:updated>2021-06-11T08:09:18.532Z</atom:updated>
            <content:encoded><![CDATA[<h3>XGboost, Naive Bayes and SVM Machine learning algorithms for facilitating title-abstract screening in systematic reviews: predicting inclusion/exclusion of abstracts</h3><h3>Introduction</h3><p>Several thousands of papers are being published every day. A paper published about a decade ago wrote “the total number of scientific papers published since 1665 passed 50 million. About 2.5 million new scientific papers are published each year.” In the introduction section of one of <a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6305167/">my previous systematic review</a>, I wrote “The number of published research doubles every 9 years and its growth particularly in medicine and health care is exponential.”</p><p>Doing systematic reviews on a certain topic requires an extensive database search, title/abstract screening, full-text screening, quality assessment, data extraction, qualitative, quantitative synthesis, and other important steps. Of these steps, at least title/abstract screening and full-text reviews are required to be done by two review authors.</p><p>Going through the title and abstract of thousands of papers is time-taking, and laborious. Yet, policymakers medical practitioners require the latest evidence for making urgent decisions. Thanks to the development of machine learning and artificial intelligence over the past decade, systematic reviews can be used to automate or semi-automate some of the steps of systematic reviews. Systematic reviewers are already using some web-based text mining and machine learning tools such as Abstrackr, Robotreviewer, RobotAnalyst, etc. However, it is worth a try to implement text classification algorithms in R.</p><p>In a paper <a href="https://arxiv.org/abs/1602.04938">“Why Should I Trust You?”: Explaining the Predictions of Any Classifier”</a>, Riberio TL et.al described machine learning models as mostly “black boxes”. The biggest challenge of machine learning is interpretability and applying it to the local contexts or simply to an individual or observation with specific characteristics. They developed LIME which was later changed into Python and R packages. Lime can help explain several models implemented in about six different packages including caret, h2o, and xgboost.</p><p>In this blog post, I want to try one of the many available methods available to check whether machine learning methods correctly discriminates SARS papers from COVID19 papers. I know the two viruses are highly related. I am only using the SARS and COVID for demonstrations.</p><pre><a href="https://rdrr.io/r/base/library.html">library</a>(<a href="https://dplyr.tidyverse.org/">dplyr</a>) #for data management<br><a href="https://rdrr.io/r/base/library.html">library</a>(<a href="http://ggplot2.tidyverse.org/">ggplot2</a>) #for plotting<br><a href="https://rdrr.io/r/base/library.html">library</a>(<a href="https://docs.ropensci.org/bib2df">bib2df</a>) #for converting bib file to data frame<br><a href="https://rdrr.io/r/base/library.html">library</a>(<a href="https://github.com/dmlc/xgboost">xgboost</a>) # for building extreme gradient boosting <br><a href="https://rdrr.io/r/base/library.html">library</a>(<a href="https://lime.data-imaginist.com/">lime</a>) #for explaining the machine learning models</pre><h3>Data</h3><p>I used the covid19 data that I used in my previous <a href="http://www.mihiretukebede.com/posts/2020-08-03-2020-08-03-covid19/">blog post</a>. In addition, I have added new reference data by searching SARS papers published from January 1/2003 until September 12/2003.</p><p>As I did in my last blog, I read my files using the beautiful bib2df package. You can also use <strong>bibliometrix</strong> or <strong>revtools</strong> packages to convert BibTeX files to a data frame in R. With <strong>revtools</strong>, you can also convert <em>.ris</em> files to the data frame. Awesome! 😍</p><pre># library(bib2df)<br># library(dplyr)<br># <br># covid &lt;- bib2df(&quot;covid19.bib&quot;) %&gt;% # import references<br>#   filter(!is.na(ABSTRACT)) %&gt;% # select only papers with no missing abstract<br>#   select(&quot;TITLE&quot;, &quot;ABSTRACT&quot;, &quot;KEYWORDS&quot;, &quot;AUTHOR&quot;, &quot;BIBTEXKEY&quot;) # Select few variables <br>#   <br># <br># # 2003 corona virus<br># covexclude &lt;- bib2df(&quot;covexclude.bib&quot;) %&gt;% <br>#   filter(!is.na(ABSTRACT)) %&gt;% <br>#   select(&quot;TITLE&quot;, &quot;ABSTRACT&quot;, &quot;KEYWORDS&quot;, &quot;AUTHOR&quot;, &quot;BIBTEXKEY&quot;)<br># <br># cov2003 &lt;- bib2df(&quot;cov2003.bib&quot;) %&gt;% <br>#   filter(!is.na(ABSTRACT)) %&gt;% <br>#   select(&quot;TITLE&quot;, &quot;ABSTRACT&quot;, &quot;KEYWORDS&quot;, &quot;AUTHOR&quot;, &quot;BIBTEXKEY&quot;)<br># <br># # Now import the TB data<br># sars &lt;- bib2df(&quot;sars.bib&quot;) %&gt;% <br>#   filter(!is.na(ABSTRACT)) %&gt;% <br>#   select(&quot;TITLE&quot;, &quot;ABSTRACT&quot;, &quot;KEYWORDS&quot;, &quot;AUTHOR&quot;, &quot;BIBTEXKEY&quot;)</pre><p>Assume we are only looking for COVID19 papers to include in our review. That means we will need to exclude all SARS papers published in 2003. I used simple include/exclude decisions.</p><p>We will now create a new binary factor variable called “Include”. We will then assign 1 for all covid papers and 0 for all SARS papers. To make the decisions look more in a real-world setting, I excluded 40 COVID papers published in August 22/2020. This has nothing to do with the contents of the papers. I am arbitrarily excluding the papers to make it look like a real-world title/abstract screening process rather than a random decision.</p><p>After that, I merged the two data frames with a simple rbind() code. I had a problem rendering UTF-8 characters on my GitHub page for this blog post. So I have instead read everything using bib2df and then from there, I wrote them in xlsx file. After that, I simply read my excel file in R and did the whole analysis using the excel file.</p><pre># Exclude all covid papers<br># covid$Include &lt;- 1 # coded them as included<br># <br># covexclude$Include &lt;- 0 # excluded<br># <br># cov2003$Include &lt;- 1 # included<br># sars$Include &lt;- 0 # excluded<br># <br># # Now merge the tw data frames<br># covid_sars &lt;- rbind(covid, covexclude, sars, cov2003) # combine<br># </pre><pre># write.xlsx(covid_sars, file = &quot;covidsars.xlsx&quot;,<br>#            sheetName = &quot;covidsars&quot;, append = FALSE)</pre><pre><a href="https://rdrr.io/r/base/library.html">library</a>(<a href="https://readxl.tidyverse.org/">readxl</a>)<br><a href="https://rdrr.io/r/base/library.html">library</a>(<a href="https://dplyr.tidyverse.org/">dplyr</a>)<br>covid_sars &lt;- <a href="https://readxl.tidyverse.org/reference/read_excel.html">read_excel</a>(&quot;covidsars.xlsx&quot;)<br><a href="https://tibble.tidyverse.org/reference/glimpse.html">glimpse</a>(covid_sars)</pre><pre>Rows: 983<br>Columns: 7<br>$ ...1     &lt;chr&gt; &quot;1&quot;, &quot;2&quot;, &quot;3&quot;, &quot;4&quot;, &quot;5&quot;, &quot;6&quot;, &quot;7&quot;, &quot;8&quot;, &quot;9&quot;, &quot;10...<br>$ title    &lt;chr&gt; &quot;Factors determining the diffusion of COVID-19 a...<br>$ abstract &lt;chr&gt; &quot;This study has two goals. The first is to expla...<br>$ keywords &lt;chr&gt; &quot;Air Pollutants,Air Pollution,Betacoronavirus,Ci...<br>$ author   &lt;chr&gt; &quot;Coccia, Mario&quot;, &quot;Ataguba, Ochega A and Ataguba,...<br>$ label    &lt;chr&gt; &quot;Coccia2020&quot;, &quot;Ataguba2020&quot;, &quot;Sigala2020&quot;, &quot;Lech...<br>$ Include  &lt;chr&gt; &quot;included&quot;, &quot;included&quot;, &quot;included&quot;, &quot;included&quot;, ...</pre><pre>#of characters<br>covid_sars$abstract_length &lt;- <a href="https://rdrr.io/r/base/nchar.html">nchar</a>(covid_sars$abstract)<br><a href="https://rdrr.io/r/base/summary.html">summary</a>(covid_sars$abstract_length)</pre><pre>Min. 1st Qu.  Median    Mean 3rd Qu.    Max. <br>     11     812    1239    1244    1620    4259</pre><pre># Select only records with more than 300 characters </pre><pre>covid_sars &lt;- covid_sars %&gt;% <br>  <a href="https://dplyr.tidyverse.org/reference/filter.html">filter</a>(abstract_length &gt; 200)</pre><h3>Check the number of included/excluded papers</h3><pre><a href="https://rdrr.io/r/base/library.html">library</a>(<a href="https://dplyr.tidyverse.org/">dplyr</a>)<br><a href="https://rdrr.io/r/base/table.html">table</a>(covid_sars$Include)</pre><pre>included not included <br>         506          464</pre><pre># check the type of this variable and convert it to factor </pre><pre><a href="https://rdrr.io/r/base/typeof.html">typeof</a>(covid_sars$Include) # it is double. We have to convert it to factor variable</pre><pre>[1] &quot;character&quot;</pre><pre>covid_sars$Include[covid_sars$Include==&quot;1&quot;]&lt;-&quot;included&quot;<br>covid_sars$Include[covid_sars$Include==&quot;0&quot;]&lt;-&quot;not included&quot;</pre><pre><a href="https://rdrr.io/r/base/table.html">table</a>(covid_sars$Include) %&gt;% <a href="https://rdrr.io/r/base/proportions.html">prop.table</a>() #51% excluded, 49% included</pre><pre>included not included <br>   0.5216495    0.4783505</pre><h3>Split the data</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w4P7LDydYGWK67nV.JPG" /></figure><p>Machine learning algorithms require our data to be split into training and testing. The training data will be used to train the model and the testing data sets will be used to make predictions by deploying the model developed using the training sets. There are different ways of splitting our data into training and testing split. You may use <em>base R</em>, <em>Resample</em> or <em>Caret</em> package to easily perform this task. Here, I will use my favorite R packager: the <strong><em>Caret</em></strong> package. We will use 70/30 split which means 70% of my data will be assigned to the training set and 30% of the data will be used for test sets.</p><p>I will need to stratify my data split by my dependent variable. That means my train and test data will have exactly a similar proportion for the outcome variable responses as the original data sets. That is 51% for excluded (coded as 0) and 49% for included (coded as 1). The data is nearly balanced. We don’t have the curse of class imbalance here, awesome!</p><pre><a href="https://rdrr.io/r/base/library.html">library</a>(<a href="https://github.com/topepo/caret/">caret</a>)<br><a href="https://rdrr.io/r/base/Random.html">set.seed</a>(3456) # for reproducibility</pre><pre>trainIndex &lt;- <a href="https://rdrr.io/pkg/caret/man/createDataPartition.html">createDataPartition</a>(covid_sars$Include, p = .7, <br>                                  list = FALSE, <br>                                  times = 1)<br>train &lt;- covid_sars[ trainIndex,]<br>test  &lt;- covid_sars[-trainIndex,]<br></pre><pre><a href="https://rdrr.io/r/base/proportions.html">prop.table</a>(<a href="https://rdrr.io/r/base/table.html">table</a>(covid_sars$Include)) # outcome proportion for th original data</pre><pre>included not included <br>   0.5216495    0.4783505</pre><pre><a href="https://rdrr.io/r/base/proportions.html">prop.table</a>(<a href="https://rdrr.io/r/base/table.html">table</a>(train$Include)) # outcome proportion for training data</pre><pre>included not included <br>   0.5220588    0.4779412</pre><pre><a href="https://rdrr.io/r/base/proportions.html">prop.table</a>(<a href="https://rdrr.io/r/base/table.html">table</a>(test$Include)) # outcome proportion for testing data</pre><pre>included not included <br>   0.5206897    0.4793103</pre><pre># Cool! They have exactly similar proportions with respect to the outcome variable.</pre><h3>The nice part</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9nk5UygE-g9GoQyW.JPG" /></figure><pre><a href="https://rdrr.io/r/base/library.html">library</a>(<a href="http://text2vec.org/">text2vec</a>)</pre><pre>get_matrix &lt;- function(text) {<br>  it &lt;- <a href="https://rdrr.io/pkg/text2vec/man/itoken.html">itoken</a>(text, progressbar = FALSE)<br>  <a href="https://rdrr.io/pkg/text2vec/man/create_dtm.html">create_dtm</a>(it, vectorizer = <a href="https://rdrr.io/pkg/text2vec/man/vectorizers.html">hash_vectorizer</a>())<br>}</pre><pre>dtm_train = get_matrix(train$abstract)<br>dtm_test = get_matrix(test$abstract)</pre><pre># Create boosting model for binary classification (-&gt; logistic loss)<br># Other parameters are quite standard</pre><pre><a href="https://rdrr.io/r/base/library.html">library</a>(<a href="https://github.com/dmlc/xgboost">xgboost</a>) # I will use extreme gradient boosting algorithm for building the model. But, I will also try other algorithms in the future. </pre><pre>param &lt;- <a href="https://rdrr.io/r/base/list.html">list</a>(max_depth = 10, <br>              eta = 0.1, <br>              objective = &quot;binary:logistic&quot;, <br>              eval_metric = &quot;error&quot;, <br>              nthread = 1) # I will set the paprametres nearly similarly as it was described in the example from the package description. </pre><pre>xgb_model &lt;- <a href="https://rdrr.io/pkg/xgboost/man/xgb.train.html">xgb.train</a>(<br>  param, <br>  <a href="https://rdrr.io/pkg/xgboost/man/xgb.DMatrix.html">xgb.DMatrix</a>(dtm_train, label = train$Include==&quot;included&quot;),<br>  nrounds = 50<br>)</pre><p>Use the model to predict the test set</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*LrrFpx-6XGpeYEHW" /></figure><pre><a href="https://rdrr.io/r/base/library.html">library</a>(<a href="https://github.com/topepo/caret/">caret</a>)<br>predictions &lt;- <a href="https://rdrr.io/r/stats/predict.html">predict</a>(xgb_model, dtm_test) <br># prediction probabilities</pre><pre>predict &lt;- <a href="https://rdrr.io/r/base/ifelse.html">ifelse</a>(predictions &gt; 0.5, &quot;included&quot;, &quot;not included&quot;) # assign prediction probabilities greater than 0.5 as included and less than 0.5 as not included<br></pre><pre><a href="https://rdrr.io/pkg/caret/man/confusionMatrix.html">confusionMatrix</a>(<a href="https://rdrr.io/r/base/factor.html">as.factor</a>(predict), <a href="https://rdrr.io/r/base/factor.html">as.factor</a>(test$Include))</pre><pre>Confusion Matrix and Statistics</pre><pre>              Reference<br>Prediction     included not included<br>  included          143            9<br>  not included        8          130<br>                                          <br>               Accuracy : 0.9414          <br>                 95% CI : (0.9078, 0.9655)<br>    No Information Rate : 0.5207          <br>    P-Value [Acc &gt; NIR] : &lt;2e-16          <br>                                          <br>                  Kappa : 0.8825          <br>                                          <br> Mcnemar&#39;s Test P-Value : 1               <br>                                          <br>            Sensitivity : 0.9470          <br>            Specificity : 0.9353          <br>         Pos Pred Value : 0.9408          <br>         Neg Pred Value : 0.9420          <br>             Prevalence : 0.5207          <br>         Detection Rate : 0.4931          <br>   Detection Prevalence : 0.5241          <br>      Balanced Accuracy : 0.9411          <br>                                          <br>       &#39;Positive&#39; Class : included</pre><p>It resulted in 93.5% accuracy. In a real-world setting, this may not happen because we will work on highly related titles and abstracts. My experiment brings two somehow related documents (SARS and covid19). Although we are explicitly looking for covid papers, I assigned some of the covid papers to be excluded just to add some confusion.</p><p>Let’s pick two abstracts(Abstract #89 and #271) and see what are the most important terms of the abstract that xgboost used for its predictions. We will use <em>lime</em> package to explain the predictions</p><h3>Abstract number 89</h3><p>We need to use <em>lime::</em> to avoid conflicts with dplyrpackage</p><pre>ab_to_explain89 &lt;- <a href="https://rdrr.io/r/utils/head.html">head</a>(test[89,]$abstract, 6)</pre><pre>explainer89 &lt;- lime::<a href="https://lime.data-imaginist.com/reference/lime.html">lime</a>(ab_to_explain89, model = xgb_model, <br>                  preprocess = get_matrix)</pre><pre>explanation89 &lt;- lime::<a href="https://lime.data-imaginist.com/reference/explain.html">explain</a>(ab_to_explain89, explainer89, n_labels=1,<br>                       n_features = 7) # Set number most important features to 7</pre><pre>explanation89[, 2:10]</pre><pre># A tibble: 7 x 9<br>   case label label_prob model_r2 model_intercept model_prediction<br>  &lt;int&gt; &lt;chr&gt;      &lt;dbl&gt;    &lt;dbl&gt;           &lt;dbl&gt;            &lt;dbl&gt;<br>1     1 0          0.950    0.962           0.989            0.951<br>2     1 0          0.950    0.962           0.989            0.951<br>3     1 0          0.950    0.962           0.989            0.951<br>4     1 0          0.950    0.962           0.989            0.951<br>5     1 0          0.950    0.962           0.989            0.951<br>6     1 0          0.950    0.962           0.989            0.951<br>7     1 0          0.950    0.962           0.989            0.951<br># ... with 3 more variables: feature &lt;chr&gt;, feature_value &lt;chr&gt;,<br>#   feature_weight &lt;dbl&gt;</pre><pre>lime::<a href="https://lime.data-imaginist.com/reference/plot_features.html">plot_features</a>(explanation89)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Gv9UsCsJq1rOF7Os.png" /></figure><p>The word <strong>sars</strong> is most important word that xgb model used to predict the exclusion of this this abstract.</p><pre>lime::<a href="https://lime.data-imaginist.com/reference/text_explanations.html">plot_text_explanations</a>(explanation89)</pre><p>The COVID-19 pandemic, which has led to a flood of papers and preprints, has placed multiple challenges on academic publishing, the most obvious one being sustained integrity under the pressure to publish quickly. There are risks of this high volume-to-speed ratio. Many letters, editorials, and supposedly “peer reviewed” papers in ranked and indexed journals were published in a matter of days, suggesting that peer review was either fleeting or non-existential, or that papers were rapidly approved by editors based on their perceived interest and topicality, rather than on their intrinsic academic value. In academic publishing circles, the claim of “peer review”, when in fact it has not been conducted, is a core characteristic of “predatory publishing”, and is also a “fake” element that may undermine efforts in recent years to build trust in science’s budding serials crisis. While the world is still centrally focused on COVID-19, the issue of “predatory publishing” is being ignored, or not being given sufficient attention. The risks to the scholarly community, academic publishing and ultimately public health are at stake when exploitative and predatory publishing are left unchallenged.<br>Label predicted: 0 (94.96%)<br>Explainer fit: 0.96</p><h3>Abstract 283</h3><pre><a href="https://rdrr.io/r/base/library.html">library</a>(<a href="https://lime.data-imaginist.com/">lime</a>)</pre><pre>ab_to_explain &lt;- <a href="https://rdrr.io/r/utils/head.html">head</a>(test[283,]$abstract, 6)</pre><pre>explainer &lt;- <a href="https://lime.data-imaginist.com/reference/lime.html">lime</a>(ab_to_explain, model = xgb_model, <br>                  preprocess = get_matrix, <br>                  tokenization =default_tokenize)</pre><pre>explanation &lt;- <a href="https://lime.data-imaginist.com/reference/explain.html">explain</a>(ab_to_explain, explainer, n_labels=1,<br>                       n_features = 7) # Set number most important features to 7</pre><pre>explanation[, 2:10]</pre><pre># A tibble: 7 x 9<br>   case label label_prob model_r2 model_intercept model_prediction<br>  &lt;int&gt; &lt;chr&gt;      &lt;dbl&gt;    &lt;dbl&gt;           &lt;dbl&gt;            &lt;dbl&gt;<br>1     1 1          0.935    0.997         -0.0123            0.931<br>2     1 1          0.935    0.997         -0.0123            0.931<br>3     1 1          0.935    0.997         -0.0123            0.931<br>4     1 1          0.935    0.997         -0.0123            0.931<br>5     1 1          0.935    0.997         -0.0123            0.931<br>6     1 1          0.935    0.997         -0.0123            0.931<br>7     1 1          0.935    0.997         -0.0123            0.931<br># ... with 3 more variables: feature &lt;chr&gt;, feature_value &lt;chr&gt;,<br>#   feature_weight &lt;dbl&gt;</pre><pre><a href="https://lime.data-imaginist.com/reference/plot_features.html">plot_features</a>(explanation)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*O6ldWW7_7WQg8B7t.png" /></figure><pre><a href="https://lime.data-imaginist.com/reference/text_explanations.html">plot_text_explanations</a>(explanation)</pre><p>Background: A sound knowledge of retropubic pelvic vascular anatomy is pivotal to the successful performance of endoscopic total extraperitoneal (TEP) inguinal hernioplasty. The objective of the current study was to evaluate the incidence and anatomy of iliopubic and aberrant obturator vessels. Methods: Between July 2001 and March 2002, a prospective endoscopic evaluation of retropubic vascular anatomy was performed on patients who underwent TEP. Endoscopic photographs of the vasculature over-lying the superior pubic ramus in the recruited patients were captured on a computer. Results: The retropubic vascular anatomy of 121 patients, who underwent either unilateral (n = 100) or bilateral (n = 21) TEP was examined. The iliopubic artery and vein were invariably present in every patient, and traversed along the iliopubic tract toward the pubic symphysis. The aberrant obturator artery was present in 31 pelvic halves, giving an overall incidence of 22{\%}. The aberrant obturator vein existed between the external iliac and obturator venous system in 27{\%} (n = 38) of the 141 pelvic halves examined. The overall incidence of corona mortis, in the form of either an aberrant obturator vein or artery, was 40{\%} (n = 56). Conclusions: Iliopubic vein and artery are universal findings in every patient. Both aberrant obturator artery and vein cross the superior pubic rami, and are therefore susceptible to injuries during dissection of the Bogros space and stapling of the mesh onto Cooper’s ligament. Awareness of these aberrant vessels will help to reduce bleeding and subsequent morbidity. Tracing along the aberrant vessel can easily identify the obturator fora-men, which is an anatomic landmark that indicates an adequate inferior dissection of the preperitoneal space.<br>Label predicted: 1 (93.54%)<br>Explainer fit: 1</p><p>The word <strong>corona</strong> is used for predicting “Include” with 87% prediction probability.</p><p>The above modelling is dirty.It didn’t use only the relevant words. I will use <em>quanteda</em> package to remove all irrelavnt words.</p><pre><a href="https://rdrr.io/r/base/library.html">library</a> (<a href="https://quanteda.io/">quanteda</a>)</pre><h3>Create corpus</h3><pre><a href="https://rdrr.io/r/base/names.html">names</a>(train)</pre><pre>[1] &quot;...1&quot;            &quot;title&quot;           &quot;abstract&quot;       <br>[4] &quot;keywords&quot;        &quot;author&quot;          &quot;label&quot;          <br>[7] &quot;Include&quot;         &quot;abstract_length&quot;</pre><pre>train_data &lt;- train[, 6]  # I need only some of my variables: title, include, and label variable I don&#39;t need the rest of the variables for now. The label variable helps me to identify the papers it is written like Authoryyyy. I will use it to attach as a document identifier. </pre><pre># Now build the corpus using abstracts of the papers<br>train_corpus &lt;- <a href="https://quanteda.io/reference/corpus.html">corpus</a>(train$abstract, <br>                     docvars = <a href="https://rdrr.io/r/base/data.frame.html">data.frame</a>(abstract_label = <a href="https://rdrr.io/r/base/names.html">names</a>(train_data))) # I added the docvars to save the additional variables other than the abstract</pre><p>Similarly for the test set</p><pre><a href="https://rdrr.io/r/base/names.html">names</a>(test)</pre><pre>[1] &quot;...1&quot;            &quot;title&quot;           &quot;abstract&quot;       <br>[4] &quot;keywords&quot;        &quot;author&quot;          &quot;label&quot;          <br>[7] &quot;Include&quot;         &quot;abstract_length&quot;</pre><pre>test1 &lt;- test %&gt;% <br>  <a href="https://dplyr.tidyverse.org/reference/filter.html">filter</a>(label!=&quot;NA&quot;)</pre><pre>test_data &lt;- test1[,6] </pre><pre>test_corpus &lt;- <a href="https://quanteda.io/reference/corpus.html">corpus</a>(test1$abstract)</pre><p>Add document identifier for both test and training set data</p><pre>docid &lt;- <a href="https://rdrr.io/r/base/paste.html">paste</a>(train$label)<br><a href="https://quanteda.io/reference/docnames.html">docnames</a>(train_corpus) &lt;- docid<br><a href="https://rdrr.io/r/base/print.html">print</a>(train_corpus)</pre><pre>Corpus consisting of 680 documents and 1 docvar.<br>Ataguba2020.1 :<br>&quot;The coronavirus disease 2019 (COVID-19) pandemic has affecte...&quot;</pre><pre>Sigala2020.1 :<br>&quot;The paper aims to critically review past and emerging litera...&quot;</pre><pre>Lechner2020.1 :<br>&quot;Amidst the coronavirus pandemic, universities across the cou...&quot;</pre><pre>VanDorp2020.1 :<br>&quot;SARS-CoV-2 is a SARS-like coronavirus of likely zoonotic ori...&quot;</pre><pre>Barilla2020.1 :<br>&quot;: ACE2 receptor has a broad expression pattern in the cellul...&quot;</pre><pre>Zhang2020d.1 :<br>&quot;The nucleocapsid protein is significant in the formation of ...&quot;</pre><pre>[ reached max_ndoc ... 674 more documents ]</pre><p>Attach the document identifier also for the test set</p><pre>docidtest &lt;- <a href="https://rdrr.io/r/base/paste.html">paste</a>(test1$label)<br><a href="https://quanteda.io/reference/docnames.html">docnames</a>(test_corpus) &lt;- docidtest<br><a href="https://rdrr.io/r/base/print.html">print</a>(test_corpus)</pre><pre>Corpus consisting of 290 documents.<br>Coccia2020.1 :<br>&quot;This study has two goals. The first is to explain the geo-en...&quot;</pre><pre>Cagliani2020.1 :<br>&quot;In December 2019, a novel human-infecting coronavirus (SARS-...&quot;</pre><pre>Okba2020.1 :<br>&quot;Middle East respiratory syndrome coronavirus (MERS-CoV) is a...&quot;</pre><pre>Donthu2020.1 :<br>&quot;The COVID-19 outbreak is a sharp reminder that pandemics, li...&quot;</pre><pre>Wister2020.1 :<br>&quot;The COVID-19 global crisis is reshaping Canadian society in ...&quot;</pre><pre>Acter2020.1 :<br>&quot;According to data compiled by researchers at Johns Hopkins U...&quot;</pre><pre>[ reached max_ndoc ... 284 more documents ]</pre><h3>Tokenize</h3><p>I will create tokens and then later document feature matrix for both train and test abstract copuses. We do the same tokenization process as we did in my previous <a href="http://www.mihiretukebede.com/posts/2020-08-10-2020-08-10-text-analysis-of-covid-publications/">blog post</a>. We will remove numbers, remove punctuation, or remove a customized list of stop words</p><pre>custom_stop_words &lt;- <a href="https://rdrr.io/r/base/c.html">c</a>(&quot;background&quot;, &quot;introduction&quot;,&quot;aims&quot;, &quot;objectives&quot;, &quot;materials&quot;, &quot;methods&quot;, &quot;results&quot;, &quot;conclusions&quot;,&quot;textless&quot;, &quot;study&quot;) <br>                                      <br>train_tokens &lt;- <a href="https://quanteda.io/reference/tokens.html">tokens</a>(train_corpus, remove_punct = TRUE,<br>                  remove_numbers = TRUE)<br>train_tokens &lt;- <a href="https://quanteda.io/reference/tokens_select.html">tokens_select</a>(train_tokens, pattern = <a href="https://rdrr.io/pkg/stopwords/man/stopwords.html">stopwords</a>(&#39;en&#39;), selection = &#39;remove&#39;) # remove irrelevant words</pre><pre>train_tokens &lt;- <a href="https://quanteda.io/reference/tokens_select.html">tokens_select</a>(train_tokens, pattern = custom_stop_words, selection = &#39;remove&#39;) # remove customized list of stop words</pre><p>I do the same for the test abstract corpuses</p><pre>test_tokens &lt;- <a href="https://quanteda.io/reference/tokens.html">tokens</a>(test_corpus, remove_punct = TRUE,<br>                  remove_numbers = TRUE)<br>test_tokens &lt;- <a href="https://quanteda.io/reference/tokens_select.html">tokens_select</a>(test_tokens, pattern = <a href="https://rdrr.io/pkg/stopwords/man/stopwords.html">stopwords</a>(&#39;en&#39;), selection = &#39;remove&#39;) # remove irrelevant words</pre><pre>test_tokens &lt;- <a href="https://quanteda.io/reference/tokens_select.html">tokens_select</a>(test_tokens, pattern = custom_stop_words, selection = &#39;remove&#39;) # remove customized list of stop words</pre><h3>Construct document feature matrix for both train and test abstract tokens</h3><pre>train_dfmat &lt;- <a href="https://quanteda.io/reference/dfm.html">dfm</a>(train_tokens) <br>test_dfmat &lt;- <a href="https://quanteda.io/reference/dfm.html">dfm</a>(test_tokens)</pre><h3>Have a quick look of the two document feature matrices</h3><pre><a href="https://rdrr.io/r/utils/head.html">head</a>(train_dfmat)</pre><pre>Document-feature matrix of: 6 documents, 11,352 features (99.1% sparse) and 1 docvar.<br>             features<br>docs          coronavirus disease covid-19 pandemic affected many<br>  Ataguba2020           2       2        6        3        1    7<br>  Sigala2020            0       0        4        1        0    0<br>  Lechner2020           2       0        0        2        0    0<br>  VanDorp2020           1       0        1        1        0    0<br>  Barilla2020           1       1        2        1        0    1<br>  Zhang2020d            1       0        1        0        0    0<br>             features<br>docs          countries increasing morbidity mortality<br>  Ataguba2020         7          1         2         1<br>  Sigala2020          0          0         0         0<br>  Lechner2020         0          0         0         0<br>  VanDorp2020         1          0         0         0<br>  Barilla2020         0          0         0         0<br>  Zhang2020d          0          0         0         0<br>[ reached max_nfeat ... 11,342 more features ]</pre><pre><a href="https://rdrr.io/r/utils/head.html">head</a>(test_dfmat)</pre><pre>Document-feature matrix of: 6 documents, 6,869 features (98.4% sparse).<br>              features<br>docs           two goals first explain geo-environmental determinants<br>  Coccia2020     1     1     1       1                 1            1<br>  Cagliani2020   0     0     0       0                 0            0<br>  Okba2020       0     0     0       0                 0            0<br>  Donthu2020     0     0     0       0                 0            0<br>  Wister2020     0     0     0       0                 0            0<br>  Acter2020      1     0     0       0                 0            0<br>              features<br>docs           accelerated diffusion covid-19 generating<br>  Coccia2020             3         3        9          1<br>  Cagliani2020           0         0        0          0<br>  Okba2020               0         0        0          0<br>  Donthu2020             0         0        1          0<br>  Wister2020             0         0        4          0<br>  Acter2020              0         0        1          0<br>[ reached max_nfeat ... 6,859 more features ]</pre><pre><a href="https://rdrr.io/r/base/dim.html">dim</a>(train_dfmat) # 646 abstracts 11191 features/terms</pre><pre>[1]   680 11352</pre><pre><a href="https://rdrr.io/r/base/dim.html">dim</a>(test_dfmat) # 276 abstracts 6668 features/terms</pre><pre>[1]  290 6869</pre><pre># Or simply pass the dfm object in ndoc() or nfeat() functions<br><a href="https://quanteda.io/reference/ndoc.html">ndoc</a>(train_dfmat)</pre><pre>[1] 680</pre><pre><a href="https://quanteda.io/reference/ndoc.html">nfeat</a>(train_dfmat)</pre><pre>[1] 11352</pre><pre><a href="https://quanteda.io/reference/ndoc.html">ndoc</a>(test_dfmat)</pre><pre>[1] 290</pre><pre><a href="https://quanteda.io/reference/ndoc.html">nfeat</a>(test_dfmat)</pre><pre>[1] 6869</pre><h3>Vizualize the test and train document feature matrices</h3><p><strong><em>“When you visualize, then you materialize.” Denis Waitley</em></strong></p><p>Vizualizing the data is very importnat. Let’s see how the wordclouds look for train and test abstracts.</p><pre><a href="https://rdrr.io/r/base/library.html">library</a>(RColorBrewer)<br>pal &lt;- <a href="https://rdrr.io/pkg/RColorBrewer/man/ColorBrewer.html">brewer.pal</a>(5, &quot;Dark2&quot;)</pre><pre>textplot_wordcloud(train_dfmat, min_count = 40,max_words = 400,<br>     color = pal)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pYTrM4Pyn0biKwBO.png" /></figure><p>Similarly, for the test_dfmat</p><pre>textplot_wordcloud(test_dfmat, min_count = 20,max_words = 400,<br>     color = pal)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ioufctH6dR8RNr1A.png" /></figure><p>Both plots of the test and train data are comparable.</p><h3>Prediction using Naive Bayes model</h3><p>I need the following packages</p><pre><a href="https://rdrr.io/r/base/library.html">library</a>(<a href="https://quanteda.io/">quanteda</a>)<br><a href="https://rdrr.io/r/base/library.html">library</a>(<a href="https://github.com/quanteda/quanteda.textmodels">quanteda.textmodels</a>)<br><a href="https://rdrr.io/r/base/library.html">library</a>(<a href="https://github.com/topepo/caret/">caret</a>)</pre><pre>naive_bayes &lt;- <a href="https://rdrr.io/pkg/quanteda.textmodels/man/textmodel_nb.html">textmodel_nb</a>(train_dfmat,train$Include)<br><a href="https://rdrr.io/r/base/summary.html">summary</a>(naive_bayes)</pre><pre>Call:<br>textmodel_nb.dfm(x = train_dfmat, y = train$Include)</pre><pre>Class Priors:<br>(showing first 2 elements)<br>    included not included <br>         0.5          0.5 </pre><pre>Estimated Feature Scores:<br>             coronavirus  disease  covid-19  pandemic  affected<br>included        0.003960 0.004630 0.0138695 0.0043808 0.0005356<br>not included    0.003552 0.004461 0.0006497 0.0004331 0.0006281<br>                  many countries increasing morbidity mortality<br>included     0.0008609 0.0011478  0.0005165 0.0002104 0.0006887<br>not included 0.0007797 0.0005847  0.0001299 0.0001083 0.0007797<br>             interestingly   actions  policies   adopted    linked<br>included         9.565e-05 1.530e-04 2.678e-04 1.530e-04 0.0002487<br>not included     4.331e-05 8.663e-05 2.166e-05 2.166e-05 0.0001733<br>                social determinants   health       sdh  critical<br>included     0.0008035    7.652e-05 0.003539 1.148e-04 0.0007652<br>not included 0.0001949    1.083e-04 0.003617 2.166e-05 0.0004765<br>             inequalities  directly    within    sector distancing<br>included        3.826e-05 0.0002296 0.0005739 1.722e-04  2.870e-04<br>not included    2.166e-05 0.0001733 0.0009529 6.497e-05  6.497e-05<br>                  good   hygiene  avoiding     large gatherings<br>included     0.0002487 0.0001722 1.339e-04 0.0006887  3.826e-05<br>not included 0.0002166 0.0001299 2.166e-05 0.0005847  2.166e-05</pre><p>Since we have already our model, we can use it for predicting the test sets. Unfortunately, the features in test_dfmat which are also in train_dfmat. <em>Quanteda</em> package has one really nice function called <em>dfm_match()</em> to select only features of the testing set that also occur in the training set.</p><pre>matched_dfmat &lt;- <a href="https://quanteda.io/reference/dfm_match.html">dfm_match</a>(test_dfmat, features = <a href="https://quanteda.io/reference/featnames.html">featnames</a>(train_dfmat))</pre><pre>actual_class &lt;- test$Include<br>predicted_class &lt;- <a href="https://rdrr.io/r/stats/predict.html">predict</a>(naive_bayes, newdata = matched_dfmat)<br>tab_class &lt;- <a href="https://rdrr.io/r/base/table.html">table</a>(predicted_class, actual_class )<br>tab_class</pre><pre>actual_class<br>predicted_class included not included<br>   included          134           13<br>   not included       17          126</pre><pre><a href="https://rdrr.io/pkg/caret/man/confusionMatrix.html">confusionMatrix</a>(tab_class, mode = &quot;everything&quot;)</pre><pre>Confusion Matrix and Statistics</pre><pre>               actual_class<br>predicted_class included not included<br>   included          134           13<br>   not included       17          126<br>                                          <br>               Accuracy : 0.8966          <br>                 95% CI : (0.8556, 0.9291)<br>    No Information Rate : 0.5207          <br>    P-Value [Acc &gt; NIR] : &lt;2e-16          <br>                                          <br>                  Kappa : 0.793           <br>                                          <br> Mcnemar&#39;s Test P-Value : 0.5839          <br>                                          <br>            Sensitivity : 0.8874          <br>            Specificity : 0.9065          <br>         Pos Pred Value : 0.9116          <br>         Neg Pred Value : 0.8811          <br>              Precision : 0.9116          <br>                 Recall : 0.8874          <br>                     F1 : 0.8993          <br>             Prevalence : 0.5207          <br>         Detection Rate : 0.4621          <br>   Detection Prevalence : 0.5069          <br>      Balanced Accuracy : 0.8969          <br>                                          <br>       &#39;Positive&#39; Class : included</pre><p>Our models predicted the test data set with 89.5% accuracy. This is wonderful! The other model performance parameters are also very good. How about Support Vector Machines?</p><pre>train_svm &lt;- <a href="https://rdrr.io/pkg/quanteda.textmodels/man/textmodel_svm.html">textmodel_svm</a>(train_dfmat,train$Include, weight=&quot;uniform&quot;) # There are three weighting options. I don&#39;t have problem of class imbalance, let me just use the default &quot;uniform&quot;</pre><h3>Predict the test set using SVM model</h3><pre>Actual &lt;- test$Include<br>predicted_class_svm &lt;- <a href="https://rdrr.io/r/stats/predict.html">predict</a>(train_svm, newdata = matched_dfmat)<br>tab_class_svm &lt;- <a href="https://rdrr.io/r/base/table.html">table</a>(predicted_class_svm, Actual )<br>tab_class_svm</pre><pre>Actual<br>predicted_class_svm included not included<br>       included          146           13<br>       not included        5          126</pre><h3>Now the confusion matrix</h3><pre><a href="https://rdrr.io/pkg/caret/man/confusionMatrix.html">confusionMatrix</a>(tab_class_svm, mode = &quot;everything&quot;)</pre><pre>Confusion Matrix and Statistics</pre><pre>                   Actual<br>predicted_class_svm included not included<br>       included          146           13<br>       not included        5          126<br>                                          <br>               Accuracy : 0.9379          <br>                 95% CI : (0.9037, 0.9628)<br>    No Information Rate : 0.5207          <br>    P-Value [Acc &gt; NIR] : &lt; 2e-16         <br>                                          <br>                  Kappa : 0.8754          <br>                                          <br> Mcnemar&#39;s Test P-Value : 0.09896         <br>                                          <br>            Sensitivity : 0.9669          <br>            Specificity : 0.9065          <br>         Pos Pred Value : 0.9182          <br>         Neg Pred Value : 0.9618          <br>              Precision : 0.9182          <br>                 Recall : 0.9669          <br>                     F1 : 0.9419          <br>             Prevalence : 0.5207          <br>         Detection Rate : 0.5034          <br>   Detection Prevalence : 0.5483          <br>      Balanced Accuracy : 0.9367          <br>                                          <br>       &#39;Positive&#39; Class : included</pre><p>SVM prediction is quite remarkable. Almost 92.5% accurate prediction. This is cool. Look at the other performance measures: sensitivity, specificity, PVP, NPV, recall, precision. They are all more than 90%!</p><p>One limitation of implementing these models using <em>quanteda.textmodels</em> is we cannot benefit from the great advantages of <em>lime</em> package, we cannot use <em>lime</em> to explain our naive_bayes model locally (within abstracts) as we did it our prediction using <em>XGB</em> because <em>lime</em> currently doesn’t support <em>quanteda.textmodels</em> package. Currently, <em>lime</em> package only explains models developed using mlr, xgboost, h2o, keras, or MASSpackages.</p><h3>Final remarks</h3><p>I have tried three different models and the level of accuracy has improved through my model choices. I see lots of beautiful things that we can take advantage of NLP for systematic reviews. However, the process is quite complex, computationally expensive and we don’t know which model works best unless we experiment with several models with broad range of model parameters. I can see its tremendous potential even after such a tiny scratch on its surface. We don’t know how much I will gain in improving the prediction accuracies if I process my abstracts using *tf-idf*, n-grams, the mighty cross-validation processes, and redo my analysis with several models including deep learning, etc.<br>Thank you for reading this post. I hope you find this helpful. For more, subscribe to my <a href="https://www.youtube.com/channel/UCpHd6O1Yqz4YgcYUBfyRqKg">YouTube channel</a> and follow me on Twitter @<a href="https://twitter.com/RPy_DataScience">RPy_DataScience</a>.You can also follow me by liking <a href="https://web.facebook.com/R_Py-Data-Science-105325938441990/news_feed">R_Py Data Science</a> Facebook page.</p><h3>Contact</h3><p>Please mention @<a href="https://twitter.com/RPy_DataScience">RPy_DataScience</a> if you tweet this post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a7df05abed3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>