<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/automating-basic-eda/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://datascienceplus.com/automating-basic-eda/"> R Programming – DataScience+</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>In any model development exercise, a considerable amount of time is spent in understanding the underlying data, visualizing relationships and validating preliminary hypothesis (broadly categorized as Exploratory data Analysis). A key element of EDA involves visually analyzing the data to glean valuable insights and understand underlying relationships &amp; patterns in the data. </p>
<p>While EDA is defined more as a philosophy rather than a defined set of procedures and techniques, there is a certain set of standard analysis that you would most likely perform as part of EDA to gain an initial understanding of the data.</p>
<p>This post provides an overview of a package <code>RtutoR</code> that I had developed some time back and have recently added a few new functionalities to automate some elements of EDA. In nutshell, the functionalities provided in the package would help you:</p>
<ul>
<li>
Automatically generate common univariate and bivariate plots and summary tables by invoking a function
</li>
<li>
An output report is generated as a PowerPoint deck (using the <code>ReporterRs</code> package) containing all the plots and summary tables generated by invoking the function</li>
<li>
Finally, a Shiny App version of the function is provided as well that provides an interactive version of the resulting plots (If you want to see a quick demo of the Shiny app, you can view it <a rel="nofollow" href="https://youtu.be/UMRBuXbRyag" target="_blank">here</a>)
</li>
</ul>
<h2>Example</h2>
<p>To understand the package functionalities, let’s look at a simple example. We will consider the Titanic dataset for this example (Most of you should be familiar with this dataset. This is a commonly used practice problem in Kaggle and the dataset can be downloaded from <a rel="nofollow" href="https://www.kaggle.com/c/titanic/data" target="_blank">here</a>). The problem statement is to predict the likelihood of a passenger surviving the Titanic disaster given a set of attributes such as Passenger Age, Gender, Fare price etc.</p>
<p>Before we proceed with building a model, we first try to gain a better understanding of the underlying data. This would generally include analysis such as :</p>
<ul>
<li>
Univariate Analysis: Understand data distribution &amp; summary analysis of individual features in our dataset. For e.g. we may plot histograms of different numeric features and simple bar charts of different categorical features in our data.</li>
<li>
Bi-variate Analysis: As part of bi-variate analysis we would like to understand relationships, if any, between the target variable and features in our dataset. This also helps us validate any initial hypothesis we may have regarding the data. For eg. we may wish to know – Are the survival rates higher for males vis-a-vis females. Was the survival rate better for younger passengers compared to older ones and so on.</li>
</ul>
<p>To perform this analysis, simply invoke the <code>generate_exploratory_analysis_ppt</code> function from the package as follows:</p>
<pre>
# The function takes 3 mandatory arguments
# df - A dataframe object to be analyzed 
# target_var - The name of the target (or dependent) variable
# output_file_name = Output file name and destination path (output file is a PowerPoint deck - if only file name is provided, the file is saved in the current working directory)
library(RtutoR)
df = read.csv(&quot;train.csv&quot;) # Load the Titanic dataset
res = generate_exploratory_analysis_ppt(df,target_var = &quot;Survived&quot;,
                                         output_file_name = &quot;titanic_exp_report.pptx&quot;)
       
# If you wish to quickly test the functionality without downloading any external dataset, you could test it on one of the inbuilt datasets in R.
# For eg., using the iris dataset
res = generate_exploratory_analysis_ppt(df = iris,target_var = &quot;Species&quot;,
                                         output_file_name = &quot;iris_report.pptx&quot;)
</pre>
<h2>Function output</h2>
<p>This function generates an Exploratory analysis PowerPoint Report (titled, titanic_exp_report.pptx) comprising of various different plots and related summary tables (Univariate and Bi-variate analysis output). The demo example output report is available in the Github repository for this project and can be downloaded from <a rel="nofollow" href="https://github.com/anup50695/RtutoR/raw/master/titanic_exp_report.pptx" target="_blank">here</a>.</p>
<p>An output object (named res in the example above) is also generated – This object can be used to view the plots and tables on the R console (and to use it for any subsequent analysis)</p>
<p>To view the contents of <code>res</code> object, simply type:</p>
<pre>
names(res) 
<em># This will return
&quot;univar&quot; &quot;bivar&quot;</em>
</pre>
<p>Basically, the output object contains the univariate and bi-variate analysis output. Analysis output is further categorized into <code>plots</code> and <code>tables</code> (as can be seen if we type <code>names(res$univar)</code> or <code>names(res$bivar))</code></p>
<p>With the iris dataset example, all available univariate plots can be listed as follows:</p>
<pre>
names(res$univar$plots)
<em>&quot;Histogram - Sepal.Length&quot; &quot;Histogram - Sepal.Width&quot; &quot;Histogram - Petal.Length&quot; &quot;Histogram - Petal.Width&quot;
</em>
</pre>
<h2>A brief note on possible errors</h2>
<p>If you trying to run the example above, you may encounter couple of possible errors:</p>
<p><code>Error : .onLoad failed in loadNamespace() for ‘rJava’, details...</code> <code>ReporteRs</code> library that the <code>RtutoR</code> package uses to generate ppt, relies on <code>rJava</code> and this error is caused by a mismatched Java version (e.g. you are running 32 bit Java on a 64 bit machine). You can read more about the issue <a rel="nofollow" href="https://davidgohel.github.io/ReporteRs/articles/faq.html" target="_blank">here</a> In my case, I was able to resolve this issue by downloading and installing a 64 bit version of Java (compatible with my 64 bit machine)</p>
<p>You may get an <code>Error: Invalid column specification</code> error. This may be due to an older version of <code>tidyr</code> installed on your machine. This error should be resolved if you upgrade to the latest version of <code>tidyr</code> – You could also simply remove the package and perform a fresh install. (This is actually a bug and caused by not specifying the correct version of the dependent package. I will be fixing it in the next release so that a manual upgrade is not required)</p>
<h2>Explanation</h2>
<p>As can be seen from the output report, the key idea behind this function is to automate some of the standard exploratory and visual analysis that’s performed as part of EDA. The function needs only 3 mandatory arguments to run (There are other arguments with default values that you can alter, which we will come to later):</p>
<ul>
<li><code>df</code> –> The dataset name</li>
<li><code>target_var</code> –> The target variable (or the dependent variable)</li>
<li><code>output_file_name</code> –> The output file name for the PowerPoint deck that is generated by the function. If only the file name is provided, the output powerpoint file is saved in the current working directory. To save to a specific folder, provide the full file path. The specific plots and the summary analysis generated by the function, depends on the datatype of the feature and target variable:</ul>
<h3>For Univariate analysis</h3>
<p>If the feature is numeric, a histogram is plotted along with a five number summary table. If the feature is categorical, a bar plot is plotted indicating the count of different unique values (or factor levels) for that feature.</p>
<h3>Bi-variate analysis</h3>
<p>The specific plot that is used to plot the relationship between the Target variable and the feature again depends on the data types:</p>
<ul>
<li>Target Variable is Categorical while the Feature is Continuous (or vice versa): A box plot is used to plot the relationship</li>
<li>
Target Variable is Categorical and the Feature is also categorical: A bar plot indicating the proportions are plotted. A bar plot with proportions, rather than absolute counts, makes it easier to visualize the relationship between the feature and the target variable</li>
<li>
Both Target and Feature variable is Continuous: A scatter plot with a smoothing line is used to depict the relationship</li>
</ul>
<h3>Note</h3>
<p>Depending on the data type(s), the function uses commonly used/recommended plot types, with default settings (e.g. default bin size in the case of histograms). Depending on the nature of your data and specific requirements, additional analysis and plots may be required – For e.g. you may wish to change the bin size for Histograms, change the default smoothing function being used (in the case of scatter plots) or use a different plot to visualize relationship (for e.g. instead of a box plot, overlapping histograms or density plots can be used). The current version of the package does not support changing the default plots and settings. Hence, custom plots if required would need to separately created. However, the package also contains a plotting app that provides an automated interface for some of the most commonly used plots and functionalities in ggplot2. I had previously blogged about this functionality <a rel="nofollow" href="https://datascienceplus.com/plotting-app-for-ggplot2/" target="_blank">here</a> &amp; <a rel="nofollow" href="https://datascienceplus.com/plotting-app-for-ggplot2-part-2/" target="_blank">here</a>.</p>
<h2>Other Function Arguments</h2>
<p>Now that we have seen how the basic version of the function works, let’s look at some of the other arguments with default values that you can override. These are:</p>
<ul>
<li>
<code>n_plots_per_slide</code>: You can control the number of plots (with corresponding tables) to be included in each slide. There are 2 option – “1” or “2” with the default value being 2. If this is changed to 1, only 1 plot (and related table) is displayed on each slide.</li>
<li>
<code>plot_theme</code>: ggplot2 is used for generating all the plots that the function generates. ggplot2 has a few different plot themes to choose from, Additionally, the ggthemes package provides a whole set of different plot themes.By default, the function uses the theme_fivethirtyeight() from ggthemes. (I will talk more about the different themes available and how to choose one, when we discuss the Shiny app version of this function)</li>
<li>
<code>top_k_features</code>: If there are lot of features in your dataset, the resulting analysis and the output PowerPoint report can be massive. For eg, if there are 100 features in your dataset (and one target variable), the final output will include 200 plots and related tables (100 for Univariate and 100 for bi-variate analysis). To reduce the number of features to be considered for analysis, a simple feature screening can be performed. By default this argument is set to NULL. if feature screening is required, simply provide an integer value to this argument, indicating the number of features to be used for analysis.</li>
<li>
<code>f_screen_model</code>: This argument is relevant only if a non-null value is provided to the <code>top_f_features argument</code>. There are various different techniques for feature screening broadly classified under (a) Filter methods and (b) Wrapper methods. The function uses few of the filter methods available as part of the FSelector package. There are 4 different filtering methods provided – <code>chi.squared</code>, <code>information.gain</code>, <code>gain.ratio</code>, <code>symmetrical.uncertainty</code> (You can go through the <code>FSelector</code> documentation for more information on these filtering methods)</li>
<li>
<code>max_levels_cat_var</code>: For categorical predictors, if the no of factor levels (or unique values for character class) is greater than this argument, the variable is omitted from the analysis (The default value is 10). In our Titanic dataset example, you will see that the Passenger name variable is not included in the output because the factor levels is > 10. The default value of 10 can be changed if required, by specifying a different value to this argument.</li>
<li>
<code>group_names</code>: Often times, while plotting the relationship between the Target variable and your feature, we would also like to visualize the relationship on some additional grouping variable. For eg. we wish to visualize the relationship between Survival Rates and Age grouped as per the Gender of the passenger. This can be done by specifying additional grouping variable (or multiple grouping variables) to this argument. Please note that this would generate all possible combinations of Target Variable and Features with the grouping variable (for eg. if there are 10 features, excluding the grouping variable, 10 new plots would be created). If the number of such combinations are large, you may wish to do an initial feature selection to reduce the number of features considered for analysis.</li>
</ul>
<p>Now let’s re-invoke the function we saw previously, by altering some of the default argument values.</p>
<pre>
library(RtutoR)
res = generate_exploratory_analysis_ppt(df,target_var = &quot;Survived&quot;,
                                         top_k_features = 5,
                                         f_screen_model = &quot;information.gain&quot;,
                                         group_name = &quot;Sex&quot;,
                                         output_file_name = &quot;titanic_exp_report_2.pptx&quot;)
</pre>
<p>Compared to the previous version, there are 2 key changes that we have made:</p>
<ul>
We have considered only the top 5 features for analysis (the top 5 features are selected using the “information.gain” filtering method)</ul>
<ul> We have performed additional bi-variate analysis with a grouping variable (“Sex”) </ul>
<p>You can download the output PowerPoint report that this function generates, <a rel="nofollow" href="https://github.com/anup50695/RtutoR/raw/master/titanic_exp_report_2.pptx" target="_blank">here</a> (A screenshot is provided below for easy reference)</p>
<p><a rel="nofollow" href="https://i0.wp.com/datascienceplus.com/wp-content/uploads/2018/01/pptx-screenshot.png?ssl=1" target="_blank"><img sizes="(max-width: 490px) 100vw, 490px" src="https://i0.wp.com/datascienceplus.com/wp-content/uploads/2018/01/pptx-screenshot-490x303.png?w=450&ssl=1" alt="" class="wp-image-10526" data-recalc-dims="1"></a></p>
<h2>Shiny App version of the function</h2>
<p>The package also provides a Shiny App version of the function. You can view a demo of the app <a rel="nofollow" href="https://youtu.be/UMRBuXbRyag" target="_blank">here</a>.</p>
<p>To launch the app simply invoke the following function:</p>
<pre>
gen_exploratory_report_app(df)
</pre>
<p>Only the dataframe needs to be passed as an argument to the function. All other argument values (target_var, plot_themes etc) are provided as Input fields in the app. Once the argument values are selected or entered (and default argument values changed, if required) the Generate Report button should be clicked to generate the exploratory analysis ppt.</p>
<p>The app version of the function makes it easier to view the list of valid options for each argument – For e.g you can view the list of all available plot themes.</p>
<p>However, the key advantage of using the app version to generate the report, is the Interactive plot output that the app provides. Once the report is generated, individual plots can be displayed on the Plot Output pane. Dropdown options are provided to select any particular plot from the set of output plots.</p>
<p>However, instead of the static plots that the PowerPoint report contains, the plots displayed on the app are interactive in nature (using the <code>plotly</code> library for interactivity). This makes it ideal for exploratory analysis – For e.g. you can zoom in on a section of the plot, switch on/off specific levels in a categorical variable and so on.</p>
<h2>Conclusion</h2>
<p>I hope that the package and the functionalities that it provides help meet the desired objective of enhancing the speed and efficiency with which data analysis can be performed so that more time can be spent on value adding &amp; hard-to-automate tasks such as Feature Engineering, Insights generation, Story-telling etc.</p>
<p>Do give the package a try and in case of any issues do feel free to highlight it the Issues section of the <a rel="nofollow" href="https://github.com/anup50695/RtutoR" target="_blank">Github repository</a> for this project.</p>
<ul></ul>
<p><strong>
<p>Related Post</p>
<p></p></strong>
<ol>
<li><a rel="nofollow" href="https://datascienceplus.com/building-a-daily-bitcoin-price-tracker-with-coindeskr-and-shiny-in-r/" title="Permanent Link toBuilding a Daily Bitcoin Price Tracker with Coindeskr and Shiny in R" target="_blank">Building a Daily Bitcoin Price Tracker with Coindeskr and Shiny in R</a></li>
<li><a rel="nofollow" href="https://datascienceplus.com/getting-started-with-dplyr-in-r-using-titanic-dataset/" title="Permanent Link toGetting started with dplyr in R using Titanic Dataset" target="_blank">Getting started with dplyr in R using Titanic Dataset</a></li>
<li><a rel="nofollow" href="https://datascienceplus.com/how-to-apply-monte-carlo-simulation-to-forecast-stock-prices-using-python/" title="Permanent Link toHow to apply Monte Carlo simulation to forecast Stock prices using Python" target="_blank">How to apply Monte Carlo simulation to forecast Stock prices using Python</a></li>
<li><a rel="nofollow" href="https://datascienceplus.com/analysing-ios-app-store-itunes-reviews-in-r/" title="Permanent Link toAnalysing iOS App Store iTunes Reviews in R" target="_blank">Analysing iOS App Store iTunes Reviews in R</a></li>
<li><a rel="nofollow" href="https://datascienceplus.com/handling-happy-vs-not-happy-better-sentiment-analysis-with-sentimentr-in-r/" title="Permanent Link toHandling ‘Happy’ vs ‘Not Happy’: Better sentiment analysis with sentimentr in R" target="_blank">Handling ‘Happy’ vs ‘Not Happy’: Better sentiment analysis with sentimentr in R</a></li>
</ol>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://datascienceplus.com/automating-basic-eda/"> R Programming – DataScience+</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/xO9OnJSB1uU" height="1"></a></div>