<?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 Tim Book on Medium]]></title>
        <description><![CDATA[Stories by Tim Book on Medium]]></description>
        <link>https://medium.com/@timbook?source=rss-8f5814c40808------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*SD6RJwjue-YSYAh5</url>
            <title>Stories by Tim Book on Medium</title>
            <link>https://medium.com/@timbook?source=rss-8f5814c40808------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 16:02:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@timbook/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[Building A Custom Model in Scikit-Learn]]></title>
            <link>https://medium.com/data-science/building-a-custom-model-in-scikit-learn-b0da965a1299?source=rss-8f5814c40808------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0da965a1299</guid>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Tim Book]]></dc:creator>
            <pubDate>Fri, 14 Feb 2020 19:17:50 GMT</pubDate>
            <atom:updated>2020-02-16T16:36:57.017Z</atom:updated>
            <content:encoded><![CDATA[<p>Scikit-Learn is incredible. It allows its users to fit almost any machine learning model you can think of, plus many you may never have even heard of! All in just two lines of code!</p><p>However, it doesn’t have <em>everything</em>. For example, ordinal regression is nowhere to be found. And its deep learning capabilities are… lacking. But who cares? You can find that stuff elsewhere, right?</p><p>True. But! Scikit-Learn isn’t just modeling. There are also some really great tools to help you streamline your modeling process, such as GridSearchCV and Pipeline. These tools are invaluable, but they only work with Scikit-Learn models. Turns out, if Scikit-Learn and our Google overlords don’t give it to us directly, <strong>we can make our own custom Scikit-Learn-compliant models!</strong> And it’s easier than you think!</p><p>In this post, I’m going to build something that is conspicuously missing from Scikit-Learn: the ability to use <em>k</em>-means clustering to do <em>transfer learning</em> in a Pipeline. That is, feeding the results of clustering into a supervised learning model in order to find the optimal value <em>k</em>.</p><h3>Warning: OOP Ahead!</h3><p>This post is going to be a little technical. Specifically, I’m going to assume you have a working knowledge of object-oriented programming (OOP). That is, you know how and why to use the class Python keyword.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*W5iKFg1brCGD0CiZNZg3xg.jpeg" /><figcaption>You must have this much class to proceed.</figcaption></figure><h3>Scikit-Learn’s Template</h3><p>One of the best things about Scikit-Learn is its incredible <em>consistency</em>. Fitting one type of model is nominally the same as fitting any other type of model. That is, modeling in Scikit-Learn is as easy as:</p><pre>model = MyModel(parameters)<br>model.fit(X, y)</pre><p>And that’s it! You can now analyze your model, probably with the help of the model’s .predict() and .score() methods. In fact, there are 5 methods every Scikit-Learn estimator is guaranteed to have:</p><ul><li>.fit()</li><li>.predict()</li><li>.score()</li><li>.set_params()</li><li>.get_params()</li></ul><h3>Building Your Own</h3><p>To build our own model, we need only construct a class that has the above 5 methods and implements them in “the usual way.” That sounds like a lot of work. Luckily, Scikit-Learn does the hard work for us. In order to build our own model, we can <em>inherit</em> from a base class built into Scikit-Learn.</p><h3>Aside: Inheritance</h3><p>In OOP, if we specify that one class <strong>inherits</strong> from another, the “subclass” then gains all the methods of the “superclass.”</p><p>The syntax of inheritance looks like this:</p><pre>class Car(Vehicle):<br>    # stuff...</pre><p>A car is a type of vehicle. The Car class will include every method of the Vehicle class, plus more that we can define in the Car class definition.</p><h3>What Does Scikit-Learn Give Us?</h3><p>In order to comply with Scikit-Learn, our model needs to inherit from some mixin. A <strong>mixin</strong> is just a class that was never intended to work on its own, instead it just contains a lot of methods that you can add to your current class via inheritance. Scikit-Learn gives us one for each general type of model: RegressorMixin, ClassifierMixin, ClusterMixin, TransformerMixin, and several others we don’t need to worry about.</p><p><strong>Everything we want to build ourselves, we make it by simply overriding what we inherit!</strong></p><p>This has been a mouthful with no examples to show for it. First, a simple example. After, the motivation example using clustering.</p><h3>Example 1: The Null Model</h3><p>The null model, sometimes called the “baseline” model, is the model where you have no information besides random guessing. For example, the null model for a regression problem would be just taking the mean <em>y</em> of your training data and using that as every prediction. For classification, it’s just taking the majority class for every prediction. For example, if you had to predict whether or not someone was going to win the lottery, the null model would dictate that you <em>always</em> lose, since that is the most likely outcome.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*KIMEn6E1n9MAh38xN5VjCg.gif" /><figcaption>Fact: This is not too different from reality.</figcaption></figure><p>The null model is useful for telling how well your current model is doing. After all, if your model is good, it should beat the baseline. The null model is not built into Scikit-Learn, but it’s easy for us to implement!</p><pre>import numpy as np<br>from sklearn.base import RegressorMixin</pre><pre>class NullRegressor(<em>RegressorMixin</em>):<br>    def fit(<em>self</em>, <em>X</em>=None, <em>y</em>=None):<br>        # The prediction will always just be the mean of y<br><em>        self</em>.y_bar_ = np.mean(y)</pre><pre>    def predict(<em>self</em>, <em>X</em>=None):<br>        # Give back the mean of y, in the same<br>        # length as the number of X observations<br>        return np.ones(X.shape[0]) * <em>self</em>.y_bar_</pre><p>Easy enough! We’re now free to do the usual…</p><pre>model = NullRegressor()<br>model.fit(X, y)<br>model.predict(X)</pre><p>The important part is, our new NullRegressor is now compatible with all of Scikit-Learn’s built-in tools such as cross_val_score and GridSearchCV.</p><h3>Example 2: “Tuning” Your Clusterer Using Grid Search</h3><p>This example was borne out of curiosity, when a coworker asked me if I could “tune” a <em>k</em>-means model using GridSearchCV and Pipeline. I originally said <em>no</em>, since you would need to use the clusterer as a transformer to pass into your supervised model, which Scikit-Learn doesn’t allow for. But why let that stop us? We just learned how to hack Scikit-Learn to do whatever we want! To spell it out, essentially what I want is to create the following pipeline:</p><pre>Pipeline([<br>    (&quot;sc&quot;, StandardScaler()),<br>    (&quot;km&quot;, KMeansSomehow()),<br>    (&quot;lr&quot;, LogisticRegression()<br>])</pre><p>Where KMeansSomehow() is a clusterer used as a Scikit-Learn <em>transformer</em>. That is, it appends the onehot-encoded cluster labels to the data matrix X to then pass into our model. In order for this to work, we’ll start by defining a class that inherits from TransformerMixin. We’ll then give it the appropriate .fit(), .transform(), and .fit_transform() methods.</p><p>But to start, the initialization:</p><pre>from sklearn.base import TransformerMixin<br>from sklearn.cluster import KMeans</pre><pre>class KMeansTransformer(TransformerMixin):<br>    def __init__(self, *args, **args):<br>        self.model = KMeans(*args, **args)</pre><p>The purpose of self.model is to contain the underlying cluster model. But what are *args and **kwargs, you ask? They’re a shortcut for lazy programmers. They essentially capture all other arguments you pass into __init__() and pass them right along to KMeans(). This is essentially me saying “Whatever I pass into KMeansTransformer will also pass into KMeans, and I’m too lazy to figure out what those arguments might be in the future.”</p><p>Next, we need to give it the appropriate fitting methods:</p><pre>from self.preprocessing import OneHotEncoder</pre><pre>class KMeansTransformer(TransformerMixin):<br>    def __init__(self, *args, **args):<br>        self.model = KMeans(*args, **args)</pre><pre>    def fit(self, X):<br>        self.X = X<br>        self.model.fit(X)</pre><pre>    def transform(self, X):<br>        # Need to reshape into a column vector in order to use<br>        # the onehot encoder.<br>        cl = self.model.predict(X).reshape(-1, 1)<br>        <br>        self.oh = OneHotEncoder(<br>            categories=&quot;auto&quot;, <br>            sparse=False,<br>            drop=&quot;first&quot;<br>        )</pre><pre>        cl_matrix = self.oh.fit_transform(cl)      <br> <br>        return np.hstack([self.X, cl_matrix])</pre><pre>    def fit_transform(self, X, y=None):<br>        self.fit(X)<br>        return self.transform(X)</pre><p>And that should be it! We can now use this KmeansTransformer just like a built-in Scikit-Learn transformer. To top it off, try this example out:</p><pre>from sklearn.preprocessing import StandardScaler<br>from sklearn.linear_model import LogisticRegression<br>from sklearn.datasets import make_blobs</pre><pre>X, y = make_blobs(<br>    n_samples=100,<br>    n_features=2,<br>    centers=3<br>)</pre><pre>pipe = Pipeline([<br>    (&quot;sc&quot;, StandardScaler()),<br>    (&quot;km&quot;, KMeansTransformer()),<br>    (&quot;lr&quot;, LogisticRegression(penalty=&quot;none&quot;, solver=&quot;lbfgs&quot;))<br>])</pre><pre>pipe.fit(X, y)<br>pipe.score(X, y)<br># ==&gt; 1.0</pre><p>In less artificial examples, you might also want to use GridSearchCV to find the optimal number of clusters to pass into your logistic regression (or whatever model you have).</p><h3><strong>Conclusion</strong></h3><p>Now you should understand how to build your own custom machine learning models within the framework of Scikit-Learn, which is currently the most popular and (in many cases) powerful ML library out there.</p><p>Is this blog post pedantic? Sure. Will you ever need this? No, you probably won’t ever <em>need</em> this, but that’s not the point. This technique is used to <em>build</em> something. It takes a <em>builder</em> to recognize the need to build a more creative solution. Plus, as a wise person once put it:</p><blockquote>You are never less for knowing more.</blockquote><p>I hope you appreciate adding this tool to your tool belt. Master it, and you may just achieve true <em>Machine Learning Ascension</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*chHxLphEqqiQWLhHkiLSFw.jpeg" /><figcaption>Pictured: What we machine learners actually do every day.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0da965a1299" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/building-a-custom-model-in-scikit-learn-b0da965a1299">Building A Custom Model in Scikit-Learn</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cleaner R Code with Functional Programming]]></title>
            <link>https://medium.com/data-science/cleaner-r-code-with-functional-programming-adc37931ef7a?source=rss-8f5814c40808------2</link>
            <guid isPermaLink="false">https://medium.com/p/adc37931ef7a</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Tim Book]]></dc:creator>
            <pubDate>Tue, 19 Feb 2019 01:57:36 GMT</pubDate>
            <atom:updated>2019-02-20T18:41:31.544Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Due to a job switch, I am a recent R-to-Python convert. However, a few side-projects keep me switching between the two languages daily. In addition to giving me a headache, this daily back-and-forth has given me a lot of thought about programming paradigms. Specifically, I’ve really become an evangelist for the functional programming paradigm in R. I want to give a little insight as to what functional programming (FP) is and how it can give you superpowers (sort of).</p><h3>Why Does it Matter?</h3><p>R has a unique place in the programming world. It is used by hundreds of thousands of people every day around the world for analyzing and manipulating data. Its users are rarely trained in pure computer science and, in many cases, R code is only run once. This combination can lead R programs to be sloppy and inefficient. How did we get here? The reasoning is usually: if it works it works, right?</p><p>If this “Why change?” mentality sounds familiar, this blog post is for you. R is in fact a full (albeit domain-specific) programming language influenced by rich mathematical theory. Learning the basics of FP will help you write better code, and thus make you a better statistician, data scientist, or whatever we’ve decided to call ourselves by the time you’re reading this.</p><h3>What is Functional Programming?</h3><p>I’m not going to give a rigorous definition. You can go to <a href="https://en.wikipedia.org/wiki/Functional_programming">Wikipedia</a> for that.</p><p>Simply put, FP is exactly what it sounds like. If you are doing something more than once, it belongs in a function. In FP, functions are the primary method with which you should carry out tasks. All actions are just (often creative) implementations of functions you’ve written.</p><p>Once you get into it, the advantages become clear. Your code is easier to fix and maintain since you’ve segmented your code into easily serviceable pieces. Your code is easier to read since, if you named everything right, your code can look closer to plain English. Replacing long blocks of code with function calls can also help you cut down on <a href="https://en.wikipedia.org/wiki/Spaghetti_code">spaghetti</a> and <a href="https://en.wikipedia.org/wiki/Pyramid_of_doom_(programming)">pyramid of doom code</a>, too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*cX4jAzZ9z7PskLwl4kDf9Q.jpeg" /><figcaption>Most bad code is not this delicious</figcaption></figure><p>Ok, how can we retrain our brains for that sweet, sweet FP?</p><h3>Step 0: Learn the Basics</h3><p>In order to write a truly “functional” function, it must be <strong><em>pure</em></strong>. A pure function has two rules:</p><ul><li><strong>It must be deterministic</strong><br>That is, every time you run this function with the same inputs, it must have the same output. Every. Single. Time. “But what about functions and statistical processes with random components?” you ask? Simply set a seed, either inside the function, or let the seed be a parameter to the function. This is important for reproducible science, anyway.</li><li><strong>It can’t have side effects</strong><br>This means that your function cannot touch or change anything outside of it. This means you should probably never be using the global assignment (&lt;&lt;-) operator. Curiously, this also means the print() function disobeys FP.</li></ul><h3>Step 1: Ditch the Loops</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*JF2BsC3oPzm0Qhj-Dsw-nQ.jpeg" /></figure><p>As my grad school adviser once told me,</p><blockquote>If you’re writing loops in R, you’re probably doing something wrong.</blockquote><p>(He told me this, of course, as he was debugging my third layer of nested for loops.)</p><p>But… loops are so fundamental! Why should we seek to use them as sparingly as possible? There are two reasons, the first of which is specific to R.</p><p><strong>The Whole Language is Already Vectorized<br></strong>Even if you’ve never heard that word before, you knew this already. Vectorization is the reason you write this:</p><pre>x &lt;- 1:10<br>y &lt;- 2 * x</pre><p>instead of</p><pre>x &lt;- 1:10<br>for (i in seq_along(x)) {<br>    y &lt;- 2 * x[i]<br>}</pre><p><strong>Loops are Slow — Use Applies!</strong><br>The apply() function, and functions like it, are the building blocks upon which R’s FP capabilities are fully realized. While in most languages, loops and applies (often called “maps”) are the same speed, we’ll see dramatic speed boosts using applies in R.</p><p>R’s base has a few applies, but the really nifty ones are found in purrr. More on this later.</p><h3>Step 2: Pipes, The Tidyverse, and More Pipes</h3><p>If you haven’t heard of the Tidyverse yet, get ready to meet your new best friend. But first, let’s meet the star of the Tidyverse, the <strong><em>pipe operator</em></strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/216/1*BtqcqN2yx_hH7G6sj3-Bkw.png" /></figure><p>The pipe (%&gt;%) is an operator supplied by several different packages, but is most commonly accessed through either dplyr or tidyverse. Oh, and if you think it’s a pain to type (%&gt;%) repeatedly, RStudio gives you a shortcut: Ctrl-Shift-M.</p><p><strong>So, what does it do?</strong> Simply put, the pipe takes what’s on the left, and makes it the first argument of what’s on the right. For example:</p><pre>add &lt;- function(x, y) x + y<br>3 %&gt;% add(5) <br># 8</pre><p>This may seem more verbose than simply typing add(3, 5), but this allows you to write complex operations as <strong><em>pipelines</em></strong><em>:</em></p><pre>3 %&gt;%<br>  add(5) %&gt;%<br>  add(1) %&gt;%<br>  add(3) %&gt;%<br>  add(7)<br> <br># 19</pre><p>Too trivial? Check out this actual snippet from one of my consulting projects:</p><pre>data_clean &lt;- data_raw %&gt;%<br>  isFinal() %&gt;%<br>  dropLastFiling() %&gt;%<br>  getAccStats() %&gt;%<br>  getPctIncs() %&gt;%<br>  capOrDrop(inc_vars, cap = 3)</pre><p>You don’t need to see what the functions do to know I’m hiding a lot of complexity here. However, you can almost read this in English:</p><ul><li>Take the raw data</li><li>Get whether or not it is the last tax filing</li><li>Drop the last tax filing for each organization</li><li>Get accounting statistics</li><li>Get the year-over-year percent increases</li><li>Drop or cap these variables where appropriate (I use a cap of 300%)</li></ul><p>Without this modularization, this code would be nearly impossible to debug. Got a problem dropping the last tax filings for each organization? You’ll have to read through hundreds of lines of spaghetti code. Here, you simply find where dropLastFiling is defined, and fix it there. Furthermore, you can more clearly see what the steps are to prepare your data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/217/1*54hkaws99jTeBVvP0_b8gg.png" /></figure><p>Now, we’re ready to get started with the Tidyverse. tidyverse is actually a collection of packages, and you may not need them all. Most of what we need is actually contained in dplyr.</p><p>Anyway, tidyverse is brimming with easy-to-pipe functions specifically built for common data manipulation tasks. Here are some of the most commonly used ones:</p><p>select() — Select which columns to keep (or drop)<br>filter()— Select which rows to keep (or drop)<br>arrange() — Sort data by given rows<br>rename() — Rename columns<br>mutate() — Make new rows from existing ones<br>group_by() — Organize data so that it is grouped by some categorical variable<br>summarize() — Similar to mutate() but collapses group_by()ed data into summary statistics</p><p>Example:</p><pre>mtcars %&gt;%<br>  filter(am == 0) %&gt;%         # Consider manual cars only<br>  group_by(cyl) %&gt;%           # Group them by the number of cylinders<br>  summarize(                  # Get the mean and sd of fuel<br>    mean_mpg = mean(mpg),     # economy by cylinder<br>    sd_mpg = sd(mpg)<br>  ) %&gt;%<br>  ungroup()                   # Undo effects of group_by()<br>                              # (Not always req, but good practice) <br> <br># Output:<br># A tibble: 3 x 3<br>#     cyl mean_mpg sd_mpg<br>#   &lt;dbl&gt;    &lt;dbl&gt;  &lt;dbl&gt;<br># 1     4     22.9   1.45<br># 2     6     19.1   1.63<br># 3     8     15.0   2.77</pre><h3>Step 3: Get Comfortable with Applies and Maps</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/215/1*jUBreZYtlwnJSJdGLO-v1w.png" /><figcaption>The package purrr is short for “Pure R”. The third R was added for the cat mascot, I suppose.</figcaption></figure><p>We still have a gap in our toolkit: we’re not allowed to use loops, <em>there are some tasks that aren’t vectorized for us already</em>! What’s a data analyst to do?</p><p>The solution is to use <strong><em>applies</em></strong> (also called <strong><em>maps</em></strong>). Maps take a collection of things, and apply some function to each one of those things. Here’s a diagram taken directly from RStudio’s <a href="https://maraaverick.rbind.io/banners/purrr_apply_cheatsheet_rstudio.png">purrr cheat sheet</a> <em>(Credit: </em><a href="https://twitter.com/dataandme"><em>Mara Averick</em></a><em>)</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*xjoS2DhnWR9as4npq__1ww.png" /></figure><p><em>Sidenote: The </em><em>dplyr package actually gets its name from applies. </em><em>dplyr = data + apply + R.</em></p><p>The purrr package contains a ridiculous number of maps from which to choose. <a href="https://maraaverick.rbind.io/banners/purrr_apply_cheatsheet_rstudio.png">Seriously, check out that cheatsheet</a>!</p><p><strong>Example, bringing it all together</strong>: Suppose I had a vector of strings, and I wanted to extract the longest word in each. There is no vectorized function that will do this for me. I will need to split the string by the space character and get the longest word. For dramatic effect, I also upper-case the strings and paste them back together:</p><pre>library(tidyverse)<br>library(purrr)<br> <br>sentences &lt;- c(<br>  &quot;My head is not functional&quot;,<br>  &quot;Programming is hard&quot;,<br>  &quot;Too many rules&quot;<br>)<br> <br>getLongestWord &lt;- function(words) {<br>  word_counts &lt;- str_length(words)<br>  longest_word &lt;- words[which.max(word_counts)]<br>  return(longest_word)<br>}<br> <br>sentences %&gt;% <br>  toupper() %&gt;% <br>  str_split(&#39; &#39;) %&gt;% <br>  map_chr(getLongestWord) %&gt;% <br>  str_c(collapse = &#39; &#39;)<br> <br># [1] &quot;FUNCTIONAL PROGRAMMING RULES&quot;</pre><h3>Bonus Step: Know the Lingo</h3><p>In other languages, some of the lingo of FP is built-in. Specifically, there are three higher-order functions that make their way into almost every language, functional or not: map (which we’ve already covered), reduce, and filter.</p><blockquote>A higher-order function is a function that either takes a function as an argument, returns a function, or both.</blockquote><p><strong>Filtering in R is easy.</strong> For data frames, we can use use tidyverse::filter. For most other things, we can simply use R’s vectorization. However, when all else fails, base R does indeed have a Filter() function. Example:</p><pre>Filter(function(x) x %% 2 == 0, 1:10)<br># [1]  2  4  6  8 10</pre><p><strong>Similarly, you probably won’t ever need </strong><strong>Reduce() in R</strong>. But just in case, here’s how it works: Reduce() will take a collection and a binary function (ie, takes two parameters), and successively applies that function two-at-a-time along that collection, cumulatively. Example:</p><pre>wrap &lt;- function(a, b) paste0(&quot;(&quot;, a, &quot; &quot;, b, &quot;)&quot;)<br>Reduce(wrap, c(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;, &quot;E&quot;))<br># [1] &quot;((((A B) C) D) E)&quot;</pre><p>Another beloved FP topic is that of <strong><em>currying</em></strong>. Currying is the act of taking a function with many arguments, and breaking it out into functions that take a partial amount of those arguments. These are sometimes called <strong><em>partial functions</em></strong>. The following example uses a <strong><em>function factory</em></strong> to make partial functions:</p><pre># Adder is a &quot;function factory&quot; - a function that makes new functions.<br>adder &lt;- function(a) {<br>    return(function(b) a + b)<br>}<br> <br># Function factory pumping out new functions.<br>add3 &lt;- adder(3)<br>add5 &lt;- adder(5)<br> <br>add3(add5(1))<br># 9</pre><p>Do you find this concept hard to follow? You’re not alone. To make this slightly more readable, the functional library gives you an explicitly currying builder:</p><pre>library(functional)<br>add &lt;- function(a, b) a + b<br>add3 &lt;- Curry(add, a = 3)<br>add5 &lt;- Curry(add, a = 5)<br> <br>add3(add5(1))<br># 9</pre><p><em>Sidenote: The verb “currying” comes from Haskell Curry, famed Mathematician/Computer Scientist/Fellow Penn Stater.</em></p><h3>Summary</h3><p>Do you feel smarter? More powerful? Ready to torture your data with some of your new FP skills? Here are some of the big takeaways:</p><ul><li>No more loops! Ever!</li><li>Anytime you want to use a loop, find the appropriate apply/map.</li><li>Integrate the Tidyverse into your workflow wherever possible.</li><li>Use the pipe (%&gt;%) when applying several functions to one thing (eg, a data frame being manipulated in the Tidyverse).</li></ul><p>Adhering to these mindsets while coding can greatly reduce ugly, difficult-to-maintain spaghetti code. Bottling things in functions can leave you with clean, readable, modular <em>ravioli code</em>. I’ll leave you with a famous quote from John Woods:</p><blockquote>Always code as if the [person] who ends up maintaining your code will be a violent psychopath who knows where you live.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*hm-_PVbSJ2xmtQ-tBEEvWw.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adc37931ef7a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/cleaner-r-code-with-functional-programming-adc37931ef7a">Cleaner R Code with Functional Programming</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>