<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/cats-are-great-and-so-is-the-forcats-r-package/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://sw23993.wordpress.com/2018/03/28/cats-are-great-and-so-is-the-forcats-r-package/"> Environmental Science and Data Analytics</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>Cats are great. Perhaps Hadley Wickham and Lionel Henry think so too given the wonderful choice of name for their purrr package. Hadley Wickham has also created a superb package called forcats, likely  an abbreviation of “for categoricals” but wittingly cat-themed, which is very, very useful to the data scientist.</p>
<p>In the data science profession, one spends a vast amount of time getting data into a clean, tidy format (aka preprocessing) for subsequent statistical analysis and modelling. If I were to estimate how much of my work life is spent doing this, I would say 70-80% at least. This is often the main difference between university and real world application. The datasets used in learning are nice and clean whereas those you encounter in the real world are far from it. I really enjoy data preprocessing and the problems that arise. I have found a handful of functions from the forcats package to be incredibly useful when working with categorical data, or factors, in R.</p>
<p><strong>Prepare some demonstration data </strong></p>
<p>A simple dataset is created using the following code. There are 50 NAs and 7 factor levels in the sales variable.</p>
<pre>library(dplyr) # Also load up dplyr so we can use the pipe operator: %>%
library(forcats)

df &lt;- data_frame(sales = factor(rep(c(&quot;Online&quot;,
 &quot;Post&quot;,
 &quot;Web&quot;,
 &quot;Call Centre&quot;,
 &quot;Inbound Phone&quot;,
 &quot;Outbound Phone&quot;,
 &quot;Field Sales&quot;,
 NA), 50)),
 buy = sample(c(0, 1), 400, replace = T)) %>%
 mutate(sales = sample(sales, size = length(sales), replace = T))

table(df$sales)</pre>
<p><strong>Dealing with missing data (NAs)</strong></p>
<p>Missing values are a common occurrence in real world data. In an R dataframe, they need to be considered when performing statistical computations on continuous data such as calculating the mean, median, variance, standard deviation, etc. In addition, when you have a dataset from which you want to build a model you may need to treat NAs in order to retain particular variables and/or prevent the loss of data due to incomplete cases. Common strategies involve imputing the mean or median (continuous) or, if categorical, the mode. However, in some cases this is not appropriate and you may need to set NAs as an explicit factor level. With forcats::fct_explicit_na() we can achieve this in a one-liner. Let’s try it out on the sales variable in our test data….</p>
<pre>df$sales &lt;- fct_explicit_na(df$sales)

table(df$sales)</pre>
<p>The NAs are now represented by an explicit level and NA values are simply replaced by (Missing). The new level can be named whatever you like by passing a name to the na_level argument….</p>
<pre>df$sales &lt;- fct_explicit_na(df$sales, na_level = &quot;My New Level&quot;)</pre>
<p><strong>Synonymous factor levels</strong></p>
<p>Sometimes a categorical variable may have two or more factor levels that refer to the same group. There may be subtle differences in syntax such as upper case leading letter versus lower case leading letter (GroupA vs. groupA), for example. In this situation, one can use forcats::fct_collapse() to collapse the synonymous levels into one. In our test data, let’s assume that Web and Online refer to the same sales channel and we want to combine both into a factor level called Online….</p>
<pre>df$sales &lt;- fct_collapse(df$sales, Online = c(&quot;Online&quot;, &quot;Web&quot;))</pre>
<p><strong>Lumping infrequent factor levels into one level </strong></p>
<p>Another situation can occur whereby one wants to analyse or model using groups of data where large sample sizes are necessary for statistical significance. Imagine a factor variable with 20 levels but just 5 of these account for over 90% of the observations in a dataset. You might drop these observations entirely but the loss of data should be avoided if possible. Alternatively, you could lump the infrequent levels into one level which covers them all, preserving the rest of the attributes associated with those observations and enabling you to tidy up the group levels. The function lumps all infrequent levels into the default level Other while ensuring that the count associated with this level remains the lowest of the levels. The user can also specify the number of levels to be kept after lumping by using the n argument. In our test data, the level Outbound Phone is the least frequent so it is lumped into the new level Other….</p>
<pre>df$sales &lt;- fct_lump(df$sales)</pre>
<p><strong>Reordering bars in a ggplot2 barplot</strong></p>
<p>The tidyverse is a suite of packages which contains dplyr, ggplot2 and forcats among others. The packages make up a wonderful ecosystem of tools for a data scientist and I would like to demonstrate how one more function, forcats::fct_infreq(), can be used with ggplot2 during the exploratory data analyis/data presentation stage. Reordering factors in a barplot can be somewhat tricky but is made easy using the forcats package….</p>
<pre>library(ggplot2)

ggplot(df, aes(x = fct_infreq(sales))) + geom_bar()</pre>
<p><img data-orig-file="https://sw23993.files.wordpress.com/2018/03/plot.png?w=456" data-orig-size="616,451" data-medium-file="https://sw23993.files.wordpress.com/2018/03/plot.png?w=456?w=300" data-attachment-id="2225" data-image-meta="{" data-image-description="" src="https://sw23993.files.wordpress.com/2018/03/plot.png?w=456" data-permalink="https://sw23993.wordpress.com/2018/03/28/cats-are-great-and-so-is-the-forcats-r-package/plot/" data-large-file="https://sw23993.files.wordpress.com/2018/03/plot.png?w=456?w=616" alt="plot" data-image-title="plot" sizes="(max-width: 616px) 100vw, 616px" data-comments-opened="1" class="wp-image-2225" data-recalc-dims="1"><br>
The factor levels are now sorted by decreasing frequency and (Missing) and Other are included. We have lost none of the original data by carrying out some quick preprocessing using forcats. Happy days!</p>
<p> </p>
<p> </p>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://sw23993.wordpress.com/2018/03/28/cats-are-great-and-so-is-the-forcats-r-package/"> Environmental Science and Data Analytics</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/7E3zEylj6vU" height="1"></a></div>