<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>functional programming Archives - Analytica Data Science Solutions</title>
	<atom:link href="https://analyticadss.com/tag/functional-programming/feed/" rel="self" type="application/rss+xml" />
	<link>https://analyticadss.com/tag/functional-programming/</link>
	<description>World&#039;s Leading Artificial Inelegance Company</description>
	<lastBuildDate>Sat, 26 Aug 2023 09:33:24 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>https://analyticadss.com/wp-content/uploads/2020/06/cropped-F.B-Cover-photo_V0.1-02-32x32.png</url>
	<title>functional programming Archives - Analytica Data Science Solutions</title>
	<link>https://analyticadss.com/tag/functional-programming/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Unleash the Power of Functional Programming in R with the purrr Package</title>
		<link>https://analyticadss.com/unleash-the-power-of-functional-programming-in-r-with-the-purrr-package/</link>
		
		<dc:creator><![CDATA[Aous Abdo]]></dc:creator>
		<pubDate>Fri, 14 Apr 2023 18:10:01 +0000</pubDate>
				<category><![CDATA[Artificial Intelligence]]></category>
		<category><![CDATA[Data Science]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[R Statistical Language]]></category>
		<category><![CDATA[functional programming]]></category>
		<category><![CDATA[R]]></category>
		<category><![CDATA[Rstats]]></category>
		<guid isPermaLink="false">https://analyticadss.com/?p=6138</guid>

					<description><![CDATA[<p>Introduction Welcome to our comprehensive guide on harnessing the power of the purrr package in R for functional programming. If you’re keen on elevating your R skills, you’re in for a treat. Today, we’ll be delving into the wonders of the purrr package — a lifesaver for functional programming. With the avalanche of data we encounter nowadays, having the [&#8230;]</p>
<p>The post <a href="https://analyticadss.com/unleash-the-power-of-functional-programming-in-r-with-the-purrr-package/">Unleash the Power of Functional Programming in R with the purrr Package</a> appeared first on <a href="https://analyticadss.com">Analytica Data Science Solutions</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading has-medium-font-size" id="9372">Introduction</h2>



<p id="dd36">Welcome to our comprehensive guide on harnessing the power of the <code>purrr</code> package in R for functional programming. If you’re keen on elevating your R skills, you’re in for a treat. Today, we’ll be delving into the wonders of the <code>purrr</code> package — a lifesaver for functional programming. With the avalanche of data we encounter nowadays, having the right tools for efficient data wrangling is paramount. If you’ve dabbled in R, you might’ve felt certain built-in functions lacking, especially when grappling with intricate operations.</p>



<p id="a3fa">This is where <code>purrr</code> strides in, offering a plethora of robust tools to fine-tune your code, making it not only clearer but also more sustainable.</p>



<p id="e548">Throughout this article, we’ll journey through the intricacies of the <code>purrr</code> package, elucidate its fundamental functions, and showcase its real-world applicability. We’ll also touch on how it can enrich your experience with R, making it more fruitful. By the time you reach the end, you’ll be well-versed in the magic of <code>purrr</code> and ready to wield its power in your data endeavors. Let’s embark on this insightful voyage into the realm of R and unravel the capabilities of the <code>purrr</code> package.</p>



<hr class="wp-block-separator has-alpha-channel-opacity is-style-dots"/>



<h2 class="wp-block-heading has-medium-font-size" id="e803"><strong>What is functional programming and why is it useful?</strong></h2>



<p id="fd43">Functional programming isn’t merely a way to write code; it’s a philosophical shift that guides how we approach computation. By treating computation as the evaluation of mathematical functions, it foregoes changes to the state and avoids mutable data. Instead, it thrives on pure functions that take given inputs and produce predictable outputs, devoid of side effects. The outcome? Code that’s more modular, predictable, and test-friendly.</p>



<p id="0e06">Now, if you’re working with R, particularly for data manipulation and analysis, functional programming can be a game-changer. It lets you create more coherent and succinct code, and here’s how:</p>



<ol class="wp-block-list">
<li>Enhanced Readability and Sustainability: Decomposing complex procedures into smaller, more digestible functions improves the understandability of your code. Plus, it’s easier to tweak as needed.</li>



<li>Boosted Productivity: By steering clear of traps like global variables, which may lead to unforeseen behaviors and debugging headaches, functional programming saves time and frustration.</li>



<li>Optimized Performance: Embracing functional programming could also enhance the efficiency of your code. It prompts the use of vectorized operations and cuts down on the necessity for explicit loops.</li>
</ol>



<p id="b77b">Eager to tap into these benefits? Read on! We’ll dive into the <code>purrr</code> package, an invaluable asset for adopting functional programming in R. Through its power, you can not only elevate your data manipulation and analysis routines but also bring more enjoyment and effectiveness to your programming journey.</p>



<hr class="wp-block-separator has-alpha-channel-opacity is-style-dots"/>



<h2 class="wp-block-heading has-medium-font-size" id="3fdc">Exploring the <code>purrr </code>package</h2>



<p id="283b">Belonging to the tidyverse collection, the <code>purrr</code>package serves as R’s gateway to functional programming. It’s packed with dynamic functions crafted to ease tasks when working with lists and a variety of data structures. Adopting <code>purrr</code>ensures that your data transformation, summarization, and manipulation processes benefit from a unified and logical syntax.</p>



<p id="382c">Let’s delve into what sets <code>purrr</code>apart:</p>



<ol class="wp-block-list">
<li>Uniformity in Function Naming: One of <code>purrrs’</code> strengths is its organized naming structure, simplifying the task of recalling and employing its functions.</li>



<li>Proficiency with Complex Data Structures: Be it nested lists, data frames, or any layered data structure, <code>purrr</code>stands out in its management capabilities.</li>



<li>Robust Error Management: Real-world data can be messy. <code>purrr</code>lends a hand by equipping you with functions that elegantly tackle errors and unexpected scenarios.</li>



<li>Harmony with <code>tidyverse</code> Companions: A significant advantage is <code>purrr</code>compatibility with renowned <code>tidyverse</code> allies such as <code>dplyr</code>, <code>tidyr</code>, and <code>ggplot2</code>. This cohesion allows for a smoother integration of functional programming into your prevailing data routines.</li>
</ol>



<p id="298a">Keen to commence your <code>purrr</code>journey? Simply fetch it from CRAN and initialize it in your R workspace.</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#F8F8F2;--cbp-line-number-width:7.708335876464844px;line-height:1.25rem"><span style="display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#272822"><svg xmlns="http://www.w3.org/2000/svg" width="54" height="14" viewBox="0 0 54 14"><g fill="none" fill-rule="evenodd" transform="translate(1 1)"><circle cx="6" cy="6" r="6" fill="#FF5F56" stroke="#E0443E" stroke-width=".5"></circle><circle cx="26" cy="6" r="6" fill="#FFBD2E" stroke="#DEA123" stroke-width=".5"></circle><circle cx="46" cy="6" r="6" fill="#27C93F" stroke="#1AAB29" stroke-width=".5"></circle></g></svg></span><span role="button" tabindex="0" data-code="install.packages(&quot;purrr&quot;)
library(purrr)" style="color:#F8F8F2;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki monokai" style="background-color: #272822" tabindex="0"><code><span class="line"><span style="color: #66D9EF">install.packages</span><span style="color: #F8F8F2">(</span><span style="color: #E6DB74">&quot;purrr&quot;</span><span style="color: #F8F8F2">)</span></span>
<span class="line"><span style="color: #66D9EF">library</span><span style="color: #F8F8F2">(purrr)</span></span></code></pre></div>



<p id="51fd">In the next section, we will dive into the core functions provided by the <code>purrr</code> package and demonstrate their usage with practical examples.</p>



<hr class="wp-block-separator has-alpha-channel-opacity is-style-dots"/>



<h2 class="wp-block-heading has-medium-font-size" id="b5b5"><strong>Core functions in purrr</strong></h2>



<p id="3c30">In this section, we will cover some of the most important and widely used functions in the <code>purrr</code> package, along with examples to demonstrate their usage.</p>



<p id="ac1b"> <strong>A. The map() family</strong></p>



<p id="0f09">The <code>map()</code> family of functions is the heart of the <code>purrr</code> package. These functions allow you to apply a function to each element of a list or a vector and return the results in a specified format.</p>



<ul class="wp-block-list">
<li><code>map()</code>: Returns a list.</li>



<li><code>map_lgl()</code>: Returns a logical vector.</li>



<li><code>map_int()</code>: Returns an integer vector.</li>



<li><code>map_dbl()</code>: Returns a double vector.</li>



<li><code>map_chr()</code>: Returns a character vector.</li>



<li><code>map_df()</code>: Returns a data frame.</li>
</ul>



<p id="e748">Example:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#F8F8F2;--cbp-line-number-width:7.7083282470703125px;line-height:1.25rem"><span style="display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#272822"><svg xmlns="http://www.w3.org/2000/svg" width="54" height="14" viewBox="0 0 54 14"><g fill="none" fill-rule="evenodd" transform="translate(1 1)"><circle cx="6" cy="6" r="6" fill="#FF5F56" stroke="#E0443E" stroke-width=".5"></circle><circle cx="26" cy="6" r="6" fill="#FFBD2E" stroke="#DEA123" stroke-width=".5"></circle><circle cx="46" cy="6" r="6" fill="#27C93F" stroke="#1AAB29" stroke-width=".5"></circle></g></svg></span><span role="button" tabindex="0" data-code="# Define a list of numbers
number_list <- list(1, 2, 3, 4)

# Square each number using map()
squared_numbers <- map(number_list, ~ .x^2)
print(squared_numbers)" style="color:#F8F8F2;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki monokai" style="background-color: #272822" tabindex="0"><code><span class="line"><span style="color: #88846F"># Define a list of numbers</span></span>
<span class="line"><span style="color: #F8F8F2">number_list </span><span style="color: #F92672"><-</span><span style="color: #F8F8F2"> </span><span style="color: #66D9EF; font-style: italic">list</span><span style="color: #F8F8F2">(</span><span style="color: #AE81FF">1</span><span style="color: #F8F8F2">, </span><span style="color: #AE81FF">2</span><span style="color: #F8F8F2">, </span><span style="color: #AE81FF">3</span><span style="color: #F8F8F2">, </span><span style="color: #AE81FF">4</span><span style="color: #F8F8F2">)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #88846F"># Square each number using map()</span></span>
<span class="line"><span style="color: #F8F8F2">squared_numbers </span><span style="color: #F92672"><-</span><span style="color: #F8F8F2"> map(number_list, </span><span style="color: #F92672">~</span><span style="color: #F8F8F2"> .x</span><span style="color: #F92672">^</span><span style="color: #AE81FF">2</span><span style="color: #F8F8F2">)</span></span>
<span class="line"><span style="color: #66D9EF">print</span><span style="color: #F8F8F2">(squared_numbers)</span></span></code></pre></div>



<p id="89fb"><strong>B. pmap()</strong></p>



<p id="1c29">The <code>pmap()</code> function is used to apply a function to elements of multiple lists simultaneously.</p>



<p id="f317">Example:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#F8F8F2;--cbp-line-number-width:7.7083282470703125px;line-height:1.25rem"><span style="display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#272822"><svg xmlns="http://www.w3.org/2000/svg" width="54" height="14" viewBox="0 0 54 14"><g fill="none" fill-rule="evenodd" transform="translate(1 1)"><circle cx="6" cy="6" r="6" fill="#FF5F56" stroke="#E0443E" stroke-width=".5"></circle><circle cx="26" cy="6" r="6" fill="#FFBD2E" stroke="#DEA123" stroke-width=".5"></circle><circle cx="46" cy="6" r="6" fill="#27C93F" stroke="#1AAB29" stroke-width=".5"></circle></g></svg></span><span role="button" tabindex="0" data-code="# Define two lists
list1 <- list(1, 2, 3)
list2 <- list(4, 5, 6)

# Add corresponding elements of the two lists using pmap()
sum_list <- pmap(list(list1, list2), ~ ..1 + ..2)
print(sum_list)" style="color:#F8F8F2;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki monokai" style="background-color: #272822" tabindex="0"><code><span class="line"><span style="color: #88846F"># Define two lists</span></span>
<span class="line"><span style="color: #F8F8F2">list1 </span><span style="color: #F92672"><-</span><span style="color: #F8F8F2"> </span><span style="color: #66D9EF; font-style: italic">list</span><span style="color: #F8F8F2">(</span><span style="color: #AE81FF">1</span><span style="color: #F8F8F2">, </span><span style="color: #AE81FF">2</span><span style="color: #F8F8F2">, </span><span style="color: #AE81FF">3</span><span style="color: #F8F8F2">)</span></span>
<span class="line"><span style="color: #F8F8F2">list2 </span><span style="color: #F92672"><-</span><span style="color: #F8F8F2"> </span><span style="color: #66D9EF; font-style: italic">list</span><span style="color: #F8F8F2">(</span><span style="color: #AE81FF">4</span><span style="color: #F8F8F2">, </span><span style="color: #AE81FF">5</span><span style="color: #F8F8F2">, </span><span style="color: #AE81FF">6</span><span style="color: #F8F8F2">)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #88846F"># Add corresponding elements of the two lists using pmap()</span></span>
<span class="line"><span style="color: #F8F8F2">sum_list </span><span style="color: #F92672"><-</span><span style="color: #F8F8F2"> pmap(</span><span style="color: #66D9EF; font-style: italic">list</span><span style="color: #F8F8F2">(list1, list2), </span><span style="color: #F92672">~</span><span style="color: #F8F8F2"> ..1 </span><span style="color: #F92672">+</span><span style="color: #F8F8F2"> .</span><span style="color: #AE81FF">.2</span><span style="color: #F8F8F2">)</span></span>
<span class="line"><span style="color: #66D9EF">print</span><span style="color: #F8F8F2">(sum_list)</span></span></code></pre></div>



<p id="0ca9"><strong>C. safely(), quietly(), and possibly()</strong></p>



<p id="ee39">These functions are used to handle errors and exceptions gracefully while applying a function.</p>



<ul class="wp-block-list">
<li><code>safely()</code>: Returns a list containing the result and any error encountered.</li>



<li><code>quietly()</code>: Returns a list containing the result, any warnings, and any messages.</li>



<li><code>possibly()</code>: Returns a default value if an error is encountered.</li>
</ul>



<p id="a799">Example:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#F8F8F2;--cbp-line-number-width:7.708335876464844px;line-height:1.25rem"><span style="display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#272822"><svg xmlns="http://www.w3.org/2000/svg" width="54" height="14" viewBox="0 0 54 14"><g fill="none" fill-rule="evenodd" transform="translate(1 1)"><circle cx="6" cy="6" r="6" fill="#FF5F56" stroke="#E0443E" stroke-width=".5"></circle><circle cx="26" cy="6" r="6" fill="#FFBD2E" stroke="#DEA123" stroke-width=".5"></circle><circle cx="46" cy="6" r="6" fill="#27C93F" stroke="#1AAB29" stroke-width=".5"></circle></g></svg></span><span role="button" tabindex="0" data-code="# Define a list with numbers and a character
mixed_list <- list(1, 2, &quot;a&quot;, 3)

# Define a safely wrapped square function
safe_square <- safely(~ .x^2)

# Apply the safe_square function to the mixed_list
results <- map(mixed_list, safe_square)
print(results)" style="color:#F8F8F2;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki monokai" style="background-color: #272822" tabindex="0"><code><span class="line"><span style="color: #88846F"># Define a list with numbers and a character</span></span>
<span class="line"><span style="color: #F8F8F2">mixed_list </span><span style="color: #F92672"><-</span><span style="color: #F8F8F2"> </span><span style="color: #66D9EF; font-style: italic">list</span><span style="color: #F8F8F2">(</span><span style="color: #AE81FF">1</span><span style="color: #F8F8F2">, </span><span style="color: #AE81FF">2</span><span style="color: #F8F8F2">, </span><span style="color: #E6DB74">&quot;a&quot;</span><span style="color: #F8F8F2">, </span><span style="color: #AE81FF">3</span><span style="color: #F8F8F2">)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #88846F"># Define a safely wrapped square function</span></span>
<span class="line"><span style="color: #F8F8F2">safe_square </span><span style="color: #F92672"><-</span><span style="color: #F8F8F2"> safely(</span><span style="color: #F92672">~</span><span style="color: #F8F8F2"> .x</span><span style="color: #F92672">^</span><span style="color: #AE81FF">2</span><span style="color: #F8F8F2">)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #88846F"># Apply the safe_square function to the mixed_list</span></span>
<span class="line"><span style="color: #F8F8F2">results </span><span style="color: #F92672"><-</span><span style="color: #F8F8F2"> map(mixed_list, safe_square)</span></span>
<span class="line"><span style="color: #66D9EF">print</span><span style="color: #F8F8F2">(results)</span></span></code></pre></div>



<p id="cbfb"><strong>D. compact() and compose()</strong></p>



<p id="37ee"><code>compact()</code> is used to remove <code>NULL</code> elements from a list, while <code>compose()</code> allows you to combine multiple functions into a single function.</p>



<p id="a367">Example:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#F8F8F2;--cbp-line-number-width:15.402778625488281px;line-height:1.25rem"><span style="display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#272822"><svg xmlns="http://www.w3.org/2000/svg" width="54" height="14" viewBox="0 0 54 14"><g fill="none" fill-rule="evenodd" transform="translate(1 1)"><circle cx="6" cy="6" r="6" fill="#FF5F56" stroke="#E0443E" stroke-width=".5"></circle><circle cx="26" cy="6" r="6" fill="#FFBD2E" stroke="#DEA123" stroke-width=".5"></circle><circle cx="46" cy="6" r="6" fill="#27C93F" stroke="#1AAB29" stroke-width=".5"></circle></g></svg></span><span role="button" tabindex="0" data-code="# Define a list with NULL elements
null_list <- list(1, NULL, 2, NULL, 3)

# Remove NULL elements using compact()
clean_list <- compact(null_list)
print(clean_list)

# Compose two functions: square and increment
square <- function(x) x^2
increment <- function(x) x + 1
square_and_increment <- compose(increment, square)

# Apply the composed function to a number
result <- square_and_increment(3)
print(result)" style="color:#F8F8F2;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki monokai" style="background-color: #272822" tabindex="0"><code><span class="line"><span style="color: #88846F"># Define a list with NULL elements</span></span>
<span class="line"><span style="color: #F8F8F2">null_list </span><span style="color: #F92672"><-</span><span style="color: #F8F8F2"> </span><span style="color: #66D9EF; font-style: italic">list</span><span style="color: #F8F8F2">(</span><span style="color: #AE81FF">1</span><span style="color: #F8F8F2">, </span><span style="color: #AE81FF">NULL</span><span style="color: #F8F8F2">, </span><span style="color: #AE81FF">2</span><span style="color: #F8F8F2">, </span><span style="color: #AE81FF">NULL</span><span style="color: #F8F8F2">, </span><span style="color: #AE81FF">3</span><span style="color: #F8F8F2">)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #88846F"># Remove NULL elements using compact()</span></span>
<span class="line"><span style="color: #F8F8F2">clean_list </span><span style="color: #F92672"><-</span><span style="color: #F8F8F2"> compact(null_list)</span></span>
<span class="line"><span style="color: #66D9EF">print</span><span style="color: #F8F8F2">(clean_list)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #88846F"># Compose two functions: square and increment</span></span>
<span class="line"><span style="color: #A6E22E">square</span><span style="color: #F8F8F2"> </span><span style="color: #F92672"><-</span><span style="color: #F8F8F2"> </span><span style="color: #F92672">function</span><span style="color: #F8F8F2">(x) x</span><span style="color: #F92672">^</span><span style="color: #AE81FF">2</span></span>
<span class="line"><span style="color: #A6E22E">increment</span><span style="color: #F8F8F2"> </span><span style="color: #F92672"><-</span><span style="color: #F8F8F2"> </span><span style="color: #F92672">function</span><span style="color: #F8F8F2">(x) x </span><span style="color: #F92672">+</span><span style="color: #F8F8F2"> </span><span style="color: #AE81FF">1</span></span>
<span class="line"><span style="color: #F8F8F2">square_and_increment </span><span style="color: #F92672"><-</span><span style="color: #F8F8F2"> compose(increment, square)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #88846F"># Apply the composed function to a number</span></span>
<span class="line"><span style="color: #F8F8F2">result </span><span style="color: #F92672"><-</span><span style="color: #F8F8F2"> square_and_increment(</span><span style="color: #AE81FF">3</span><span style="color: #F8F8F2">)</span></span>
<span class="line"><span style="color: #66D9EF">print</span><span style="color: #F8F8F2">(result)</span></span></code></pre></div>



<p>These core functions are just the beginning of what <code>purrr</code> has to offer. In the next section, we will demonstrate how to use these functions to solve real-world problems through practical examples.</p>



<hr class="wp-block-separator has-alpha-channel-opacity is-style-dots"/>



<h2 class="wp-block-heading has-medium-font-size" id="4243">Practical examples with purrr</h2>



<p id="1de5">In this section, we will explore two practical examples that demonstrate how the <code>purrr</code> package can be used to solve real-world problems efficiently.</p>



<p id="3fb2"><strong>A. Example 1: Calculating summary statistics for multiple variables</strong></p>



<p id="3260">Suppose you have a data frame with multiple numerical variables, and you want to calculate summary statistics (mean, median, and standard deviation) for each of these variables.</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#F8F8F2;--cbp-line-number-width:15.40277099609375px;line-height:1.25rem"><span style="display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#272822"><svg xmlns="http://www.w3.org/2000/svg" width="54" height="14" viewBox="0 0 54 14"><g fill="none" fill-rule="evenodd" transform="translate(1 1)"><circle cx="6" cy="6" r="6" fill="#FF5F56" stroke="#E0443E" stroke-width=".5"></circle><circle cx="26" cy="6" r="6" fill="#FFBD2E" stroke="#DEA123" stroke-width=".5"></circle><circle cx="46" cy="6" r="6" fill="#27C93F" stroke="#1AAB29" stroke-width=".5"></circle></g></svg></span><span role="button" tabindex="0" data-code="# Load required packages
library(dplyr)
library(purrr)

# Create a sample data frame
data <- data.frame(
  var1 = rnorm(100, mean = 10, sd = 2),
  var2 = rnorm(100, mean = 20, sd = 5),
  var3 = rnorm(100, mean = 30, sd = 3),
  stringsAsFactors = FALSE
)

# Define a list of summary functions
summary_functions <- list(mean = mean, median = median, sd = sd)

# Calculate summary statistics for each variable using nested map functions
summary_stats <- map_dfr(summary_functions, ~ map_dfc(data, .x), .id = &quot;Statistic&quot;)
print(summary_stats)" style="color:#F8F8F2;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki monokai" style="background-color: #272822" tabindex="0"><code><span class="line"><span style="color: #88846F"># Load required packages</span></span>
<span class="line"><span style="color: #66D9EF">library</span><span style="color: #F8F8F2">(dplyr)</span></span>
<span class="line"><span style="color: #66D9EF">library</span><span style="color: #F8F8F2">(purrr)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #88846F"># Create a sample data frame</span></span>
<span class="line"><span style="color: #F8F8F2">data </span><span style="color: #F92672"><-</span><span style="color: #F8F8F2"> </span><span style="color: #66D9EF">data.frame</span><span style="color: #F8F8F2">(</span></span>
<span class="line"><span style="color: #F8F8F2">  </span><span style="color: #FD971F; font-style: italic">var1</span><span style="color: #F8F8F2"> </span><span style="color: #F92672">=</span><span style="color: #F8F8F2"> </span><span style="color: #66D9EF">rnorm</span><span style="color: #F8F8F2">(</span><span style="color: #AE81FF">100</span><span style="color: #F8F8F2">, </span><span style="color: #FD971F; font-style: italic">mean</span><span style="color: #F8F8F2"> </span><span style="color: #F92672">=</span><span style="color: #F8F8F2"> </span><span style="color: #AE81FF">10</span><span style="color: #F8F8F2">, </span><span style="color: #FD971F; font-style: italic">sd</span><span style="color: #F8F8F2"> </span><span style="color: #F92672">=</span><span style="color: #F8F8F2"> </span><span style="color: #AE81FF">2</span><span style="color: #F8F8F2">),</span></span>
<span class="line"><span style="color: #F8F8F2">  </span><span style="color: #FD971F; font-style: italic">var2</span><span style="color: #F8F8F2"> </span><span style="color: #F92672">=</span><span style="color: #F8F8F2"> </span><span style="color: #66D9EF">rnorm</span><span style="color: #F8F8F2">(</span><span style="color: #AE81FF">100</span><span style="color: #F8F8F2">, </span><span style="color: #FD971F; font-style: italic">mean</span><span style="color: #F8F8F2"> </span><span style="color: #F92672">=</span><span style="color: #F8F8F2"> </span><span style="color: #AE81FF">20</span><span style="color: #F8F8F2">, </span><span style="color: #FD971F; font-style: italic">sd</span><span style="color: #F8F8F2"> </span><span style="color: #F92672">=</span><span style="color: #F8F8F2"> </span><span style="color: #AE81FF">5</span><span style="color: #F8F8F2">),</span></span>
<span class="line"><span style="color: #F8F8F2">  </span><span style="color: #FD971F; font-style: italic">var3</span><span style="color: #F8F8F2"> </span><span style="color: #F92672">=</span><span style="color: #F8F8F2"> </span><span style="color: #66D9EF">rnorm</span><span style="color: #F8F8F2">(</span><span style="color: #AE81FF">100</span><span style="color: #F8F8F2">, </span><span style="color: #FD971F; font-style: italic">mean</span><span style="color: #F8F8F2"> </span><span style="color: #F92672">=</span><span style="color: #F8F8F2"> </span><span style="color: #AE81FF">30</span><span style="color: #F8F8F2">, </span><span style="color: #FD971F; font-style: italic">sd</span><span style="color: #F8F8F2"> </span><span style="color: #F92672">=</span><span style="color: #F8F8F2"> </span><span style="color: #AE81FF">3</span><span style="color: #F8F8F2">),</span></span>
<span class="line"><span style="color: #F8F8F2">  </span><span style="color: #FD971F; font-style: italic">stringsAsFactors</span><span style="color: #F8F8F2"> </span><span style="color: #F92672">=</span><span style="color: #F8F8F2"> </span><span style="color: #AE81FF">FALSE</span></span>
<span class="line"><span style="color: #F8F8F2">)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #88846F"># Define a list of summary functions</span></span>
<span class="line"><span style="color: #F8F8F2">summary_functions </span><span style="color: #F92672"><-</span><span style="color: #F8F8F2"> </span><span style="color: #66D9EF; font-style: italic">list</span><span style="color: #F8F8F2">(</span><span style="color: #FD971F; font-style: italic">mean</span><span style="color: #F8F8F2"> </span><span style="color: #F92672">=</span><span style="color: #F8F8F2"> mean, </span><span style="color: #FD971F; font-style: italic">median</span><span style="color: #F8F8F2"> </span><span style="color: #F92672">=</span><span style="color: #F8F8F2"> median, </span><span style="color: #FD971F; font-style: italic">sd</span><span style="color: #F8F8F2"> </span><span style="color: #F92672">=</span><span style="color: #F8F8F2"> sd)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #88846F"># Calculate summary statistics for each variable using nested map functions</span></span>
<span class="line"><span style="color: #F8F8F2">summary_stats </span><span style="color: #F92672"><-</span><span style="color: #F8F8F2"> map_dfr(summary_functions, </span><span style="color: #F92672">~</span><span style="color: #F8F8F2"> map_dfc(data, .x), </span><span style="color: #FD971F; font-style: italic">.id</span><span style="color: #F8F8F2"> </span><span style="color: #F92672">=</span><span style="color: #F8F8F2"> </span><span style="color: #E6DB74">&quot;Statistic&quot;</span><span style="color: #F8F8F2">)</span></span>
<span class="line"><span style="color: #66D9EF">print</span><span style="color: #F8F8F2">(summary_stats)</span></span></code></pre></div>



<p id="ae64"><strong>B. Example 2: Fitting multiple linear models for different subsets of data</strong></p>



<p id="c80a">In this example, we will fit linear models for different subsets of the <code>mtcars</code> dataset based on the number of cylinders. We will use <code>purrr</code> functions to apply the linear model function to each subset and extract the model coefficients.</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#F8F8F2;--cbp-line-number-width:15.402786254882812px;line-height:1.25rem"><span style="display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#272822"><svg xmlns="http://www.w3.org/2000/svg" width="54" height="14" viewBox="0 0 54 14"><g fill="none" fill-rule="evenodd" transform="translate(1 1)"><circle cx="6" cy="6" r="6" fill="#FF5F56" stroke="#E0443E" stroke-width=".5"></circle><circle cx="26" cy="6" r="6" fill="#FFBD2E" stroke="#DEA123" stroke-width=".5"></circle><circle cx="46" cy="6" r="6" fill="#27C93F" stroke="#1AAB29" stroke-width=".5"></circle></g></svg></span><span role="button" tabindex="0" data-code="# Load required packages
library(dplyr)
library(purrr)
library(broom)

# Split the mtcars dataset by the number of cylinders
mtcars_split <- mtcars %>% group_split(cyl)

# Define a function to fit a linear model and extract coefficients
fit_lm <- function(data) {
  model <- lm(mpg ~ wt, data = data)
  coef <- data.frame(tidy(model)) %>%
    select(term, estimate) %>%
    mutate(cyl = unique(data$cyl))
  return(coef)
}

# Apply the fit_lm function to each subset using map_dfr()
model_coefs <- map_dfr(mtcars_split, fit_lm)
print(model_coefs)" style="color:#F8F8F2;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki monokai" style="background-color: #272822" tabindex="0"><code><span class="line"><span style="color: #88846F"># Load required packages</span></span>
<span class="line"><span style="color: #66D9EF">library</span><span style="color: #F8F8F2">(dplyr)</span></span>
<span class="line"><span style="color: #66D9EF">library</span><span style="color: #F8F8F2">(purrr)</span></span>
<span class="line"><span style="color: #66D9EF">library</span><span style="color: #F8F8F2">(broom)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #88846F"># Split the mtcars dataset by the number of cylinders</span></span>
<span class="line"><span style="color: #F8F8F2">mtcars_split </span><span style="color: #F92672"><-</span><span style="color: #F8F8F2"> mtcars </span><span style="color: #F92672">%>%</span><span style="color: #F8F8F2"> group_split(cyl)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #88846F"># Define a function to fit a linear model and extract coefficients</span></span>
<span class="line"><span style="color: #A6E22E">fit_lm</span><span style="color: #F8F8F2"> </span><span style="color: #F92672"><-</span><span style="color: #F8F8F2"> </span><span style="color: #F92672">function</span><span style="color: #F8F8F2">(data) {</span></span>
<span class="line"><span style="color: #F8F8F2">  model </span><span style="color: #F92672"><-</span><span style="color: #F8F8F2"> </span><span style="color: #66D9EF">lm</span><span style="color: #F8F8F2">(mpg </span><span style="color: #F92672">~</span><span style="color: #F8F8F2"> wt, </span><span style="color: #FD971F; font-style: italic">data</span><span style="color: #F8F8F2"> </span><span style="color: #F92672">=</span><span style="color: #F8F8F2"> data)</span></span>
<span class="line"><span style="color: #F8F8F2">  coef </span><span style="color: #F92672"><-</span><span style="color: #F8F8F2"> </span><span style="color: #66D9EF">data.frame</span><span style="color: #F8F8F2">(tidy(model)) </span><span style="color: #F92672">%>%</span></span>
<span class="line"><span style="color: #F8F8F2">    select(term, estimate) </span><span style="color: #F92672">%>%</span></span>
<span class="line"><span style="color: #F8F8F2">    mutate(</span><span style="color: #FD971F; font-style: italic">cyl</span><span style="color: #F8F8F2"> </span><span style="color: #F92672">=</span><span style="color: #F8F8F2"> </span><span style="color: #66D9EF">unique</span><span style="color: #F8F8F2">(data</span><span style="color: #F92672">$</span><span style="color: #F8F8F2">cyl))</span></span>
<span class="line"><span style="color: #F8F8F2">  </span><span style="color: #F92672">return</span><span style="color: #F8F8F2">(coef)</span></span>
<span class="line"><span style="color: #F8F8F2">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #88846F"># Apply the fit_lm function to each subset using map_dfr()</span></span>
<span class="line"><span style="color: #F8F8F2">model_coefs </span><span style="color: #F92672"><-</span><span style="color: #F8F8F2"> map_dfr(mtcars_split, fit_lm)</span></span>
<span class="line"><span style="color: #66D9EF">print</span><span style="color: #F8F8F2">(model_coefs)</span></span></code></pre></div>



<p id="8a7a"><strong>C. Reading Multiple CSV files with purrr</strong></p>



<p id="1f79">Suppose you have multiple CSV files in a directory and you want to read them all into a single data frame using <code>purrr</code>. Here’s an example of how you can achieve this:</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#F8F8F2;--cbp-line-number-width:15.402801513671875px;line-height:1.25rem"><span style="display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#272822"><svg xmlns="http://www.w3.org/2000/svg" width="54" height="14" viewBox="0 0 54 14"><g fill="none" fill-rule="evenodd" transform="translate(1 1)"><circle cx="6" cy="6" r="6" fill="#FF5F56" stroke="#E0443E" stroke-width=".5"></circle><circle cx="26" cy="6" r="6" fill="#FFBD2E" stroke="#DEA123" stroke-width=".5"></circle><circle cx="46" cy="6" r="6" fill="#27C93F" stroke="#1AAB29" stroke-width=".5"></circle></g></svg></span><span role="button" tabindex="0" data-code="# Define the directory containing the CSV files
csv_directory <- &quot;path/to/your/csv/files&quot;

# List all CSV files in the directory
csv_files <- list.files(csv_directory, pattern = &quot;*.csv&quot;, full.names = TRUE)

# Define a function to read a CSV file and add a column with the filename
read_csv_with_filename <- function(file) {
  data <- read_csv(file)
  data <- data %>% mutate(filename = basename(file))
  return(data)
}

# Read all CSV files using map_dfr() and bind the results into a single data frame
combined_data <- map_dfr(csv_files, read_csv_with_filename)" style="color:#F8F8F2;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki monokai" style="background-color: #272822" tabindex="0"><code><span class="line"><span style="color: #88846F"># Define the directory containing the CSV files</span></span>
<span class="line"><span style="color: #F8F8F2">csv_directory </span><span style="color: #F92672"><-</span><span style="color: #F8F8F2"> </span><span style="color: #E6DB74">&quot;path/to/your/csv/files&quot;</span></span>
<span class="line"></span>
<span class="line"><span style="color: #88846F"># List all CSV files in the directory</span></span>
<span class="line"><span style="color: #F8F8F2">csv_files </span><span style="color: #F92672"><-</span><span style="color: #F8F8F2"> </span><span style="color: #66D9EF">list.files</span><span style="color: #F8F8F2">(csv_directory, </span><span style="color: #FD971F; font-style: italic">pattern</span><span style="color: #F8F8F2"> </span><span style="color: #F92672">=</span><span style="color: #F8F8F2"> </span><span style="color: #E6DB74">&quot;*.csv&quot;</span><span style="color: #F8F8F2">, </span><span style="color: #FD971F; font-style: italic">full.names</span><span style="color: #F8F8F2"> </span><span style="color: #F92672">=</span><span style="color: #F8F8F2"> </span><span style="color: #AE81FF">TRUE</span><span style="color: #F8F8F2">)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #88846F"># Define a function to read a CSV file and add a column with the filename</span></span>
<span class="line"><span style="color: #A6E22E">read_csv_with_filename</span><span style="color: #F8F8F2"> </span><span style="color: #F92672"><-</span><span style="color: #F8F8F2"> </span><span style="color: #F92672">function</span><span style="color: #F8F8F2">(file) {</span></span>
<span class="line"><span style="color: #F8F8F2">  data </span><span style="color: #F92672"><-</span><span style="color: #F8F8F2"> read_csv(file)</span></span>
<span class="line"><span style="color: #F8F8F2">  data </span><span style="color: #F92672"><-</span><span style="color: #F8F8F2"> data </span><span style="color: #F92672">%>%</span><span style="color: #F8F8F2"> mutate(</span><span style="color: #FD971F; font-style: italic">filename</span><span style="color: #F8F8F2"> </span><span style="color: #F92672">=</span><span style="color: #F8F8F2"> </span><span style="color: #66D9EF">basename</span><span style="color: #F8F8F2">(file))</span></span>
<span class="line"><span style="color: #F8F8F2">  </span><span style="color: #F92672">return</span><span style="color: #F8F8F2">(data)</span></span>
<span class="line"><span style="color: #F8F8F2">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #88846F"># Read all CSV files using map_dfr() and bind the results into a single data frame</span></span>
<span class="line"><span style="color: #F8F8F2">combined_data </span><span style="color: #F92672"><-</span><span style="color: #F8F8F2"> map_dfr(csv_files, read_csv_with_filename)</span></span></code></pre></div>



<p id="9b39">In this example, we first list all the CSV files in the specified directory. Then, we define a custom function <code>read_csv_with_filename()</code> to read each CSV file and add a column with the filename. Finally, we use <code>purrr</code>‘s <code>map_dfr()</code> function to apply the custom function to each file in the list and bind the results into a single data frame.</p>



<p id="bd14"><strong>D. purrr and ggplot2</strong></p>



<p id="78fa">In this example, we’ll demonstrate how to use <code>purrr</code> to create multiple ggplots for different subsets of data within a single data frame. We’ll use the <code>mtcars</code> dataset and create separate ggplots for each unique number of cylinders.</p>



<div class="wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#F8F8F2;--cbp-line-number-width:15.40277099609375px;line-height:1.25rem"><span style="display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#272822"><svg xmlns="http://www.w3.org/2000/svg" width="54" height="14" viewBox="0 0 54 14"><g fill="none" fill-rule="evenodd" transform="translate(1 1)"><circle cx="6" cy="6" r="6" fill="#FF5F56" stroke="#E0443E" stroke-width=".5"></circle><circle cx="26" cy="6" r="6" fill="#FFBD2E" stroke="#DEA123" stroke-width=".5"></circle><circle cx="46" cy="6" r="6" fill="#27C93F" stroke="#1AAB29" stroke-width=".5"></circle></g></svg></span><span role="button" tabindex="0" data-code="# Load required packages
library(purrr)
library(ggplot2)
library(dplyr)
library(cowplot)

# Create a list of data frames, one for each unique number of cylinders in the mtcars dataset
data_list <- mtcars %>%
  split(.$cyl)

# Define a function to create a ggplot for a given data frame
create_ggplot <- function(data) {
  ggplot(data, aes(x = mpg, y = hp)) +
    geom_point(aes(color = factor(gear)), size = 3) +
    labs(title = paste(&quot;Number of Cylinders:&quot;, unique(data$cyl)),
         x = &quot;Miles per Gallon&quot;,
         y = &quot;Horsepower&quot;) +
    theme_minimal() +
    theme(legend.title = element_blank()) +
    scale_color_discrete(name = &quot;Gears&quot;)
}

# Create a list of ggplots using map()
ggplot_list <- data_list %>% 
  map(create_ggplot)

# Combine the ggplots into a single plot using cowplot's plot_grid()
combined_plot <- plot_grid(plotlist = ggplot_list, ncol = 1, align = &quot;v&quot;, rel_heights = c(1, 1, 1))

# Display the combined plot
print(combined_plot)" style="color:#F8F8F2;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki monokai" style="background-color: #272822" tabindex="0"><code><span class="line"><span style="color: #88846F"># Load required packages</span></span>
<span class="line"><span style="color: #66D9EF">library</span><span style="color: #F8F8F2">(purrr)</span></span>
<span class="line"><span style="color: #66D9EF">library</span><span style="color: #F8F8F2">(ggplot2)</span></span>
<span class="line"><span style="color: #66D9EF">library</span><span style="color: #F8F8F2">(dplyr)</span></span>
<span class="line"><span style="color: #66D9EF">library</span><span style="color: #F8F8F2">(cowplot)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #88846F"># Create a list of data frames, one for each unique number of cylinders in the mtcars dataset</span></span>
<span class="line"><span style="color: #F8F8F2">data_list </span><span style="color: #F92672"><-</span><span style="color: #F8F8F2"> mtcars </span><span style="color: #F92672">%>%</span></span>
<span class="line"><span style="color: #F8F8F2">  </span><span style="color: #66D9EF">split</span><span style="color: #F8F8F2">(.</span><span style="color: #F92672">$</span><span style="color: #F8F8F2">cyl)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #88846F"># Define a function to create a ggplot for a given data frame</span></span>
<span class="line"><span style="color: #A6E22E">create_ggplot</span><span style="color: #F8F8F2"> </span><span style="color: #F92672"><-</span><span style="color: #F8F8F2"> </span><span style="color: #F92672">function</span><span style="color: #F8F8F2">(data) {</span></span>
<span class="line"><span style="color: #F8F8F2">  ggplot(data, aes(</span><span style="color: #FD971F; font-style: italic">x</span><span style="color: #F8F8F2"> </span><span style="color: #F92672">=</span><span style="color: #F8F8F2"> mpg, </span><span style="color: #FD971F; font-style: italic">y</span><span style="color: #F8F8F2"> </span><span style="color: #F92672">=</span><span style="color: #F8F8F2"> hp)) </span><span style="color: #F92672">+</span></span>
<span class="line"><span style="color: #F8F8F2">    geom_point(aes(</span><span style="color: #FD971F; font-style: italic">color</span><span style="color: #F8F8F2"> </span><span style="color: #F92672">=</span><span style="color: #F8F8F2"> </span><span style="color: #66D9EF">factor</span><span style="color: #F8F8F2">(gear)), </span><span style="color: #FD971F; font-style: italic">size</span><span style="color: #F8F8F2"> </span><span style="color: #F92672">=</span><span style="color: #F8F8F2"> </span><span style="color: #AE81FF">3</span><span style="color: #F8F8F2">) </span><span style="color: #F92672">+</span></span>
<span class="line"><span style="color: #F8F8F2">    labs(</span><span style="color: #FD971F; font-style: italic">title</span><span style="color: #F8F8F2"> </span><span style="color: #F92672">=</span><span style="color: #F8F8F2"> </span><span style="color: #66D9EF">paste</span><span style="color: #F8F8F2">(</span><span style="color: #E6DB74">&quot;Number of Cylinders:&quot;</span><span style="color: #F8F8F2">, </span><span style="color: #66D9EF">unique</span><span style="color: #F8F8F2">(data</span><span style="color: #F92672">$</span><span style="color: #F8F8F2">cyl)),</span></span>
<span class="line"><span style="color: #F8F8F2">         </span><span style="color: #FD971F; font-style: italic">x</span><span style="color: #F8F8F2"> </span><span style="color: #F92672">=</span><span style="color: #F8F8F2"> </span><span style="color: #E6DB74">&quot;Miles per Gallon&quot;</span><span style="color: #F8F8F2">,</span></span>
<span class="line"><span style="color: #F8F8F2">         </span><span style="color: #FD971F; font-style: italic">y</span><span style="color: #F8F8F2"> </span><span style="color: #F92672">=</span><span style="color: #F8F8F2"> </span><span style="color: #E6DB74">&quot;Horsepower&quot;</span><span style="color: #F8F8F2">) </span><span style="color: #F92672">+</span></span>
<span class="line"><span style="color: #F8F8F2">    theme_minimal() </span><span style="color: #F92672">+</span></span>
<span class="line"><span style="color: #F8F8F2">    theme(</span><span style="color: #FD971F; font-style: italic">legend.title</span><span style="color: #F8F8F2"> </span><span style="color: #F92672">=</span><span style="color: #F8F8F2"> element_blank()) </span><span style="color: #F92672">+</span></span>
<span class="line"><span style="color: #F8F8F2">    scale_color_discrete(</span><span style="color: #FD971F; font-style: italic">name</span><span style="color: #F8F8F2"> </span><span style="color: #F92672">=</span><span style="color: #F8F8F2"> </span><span style="color: #E6DB74">&quot;Gears&quot;</span><span style="color: #F8F8F2">)</span></span>
<span class="line"><span style="color: #F8F8F2">}</span></span>
<span class="line"></span>
<span class="line"><span style="color: #88846F"># Create a list of ggplots using map()</span></span>
<span class="line"><span style="color: #F8F8F2">ggplot_list </span><span style="color: #F92672"><-</span><span style="color: #F8F8F2"> data_list </span><span style="color: #F92672">%>%</span><span style="color: #F8F8F2"> </span></span>
<span class="line"><span style="color: #F8F8F2">  map(create_ggplot)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #88846F"># Combine the ggplots into a single plot using cowplot&#39;s plot_grid()</span></span>
<span class="line"><span style="color: #F8F8F2">combined_plot </span><span style="color: #F92672"><-</span><span style="color: #F8F8F2"> plot_grid(</span><span style="color: #FD971F; font-style: italic">plotlist</span><span style="color: #F8F8F2"> </span><span style="color: #F92672">=</span><span style="color: #F8F8F2"> ggplot_list, </span><span style="color: #FD971F; font-style: italic">ncol</span><span style="color: #F8F8F2"> </span><span style="color: #F92672">=</span><span style="color: #F8F8F2"> </span><span style="color: #AE81FF">1</span><span style="color: #F8F8F2">, </span><span style="color: #FD971F; font-style: italic">align</span><span style="color: #F8F8F2"> </span><span style="color: #F92672">=</span><span style="color: #F8F8F2"> </span><span style="color: #E6DB74">&quot;v&quot;</span><span style="color: #F8F8F2">, </span><span style="color: #FD971F; font-style: italic">rel_heights</span><span style="color: #F8F8F2"> </span><span style="color: #F92672">=</span><span style="color: #F8F8F2"> </span><span style="color: #66D9EF">c</span><span style="color: #F8F8F2">(</span><span style="color: #AE81FF">1</span><span style="color: #F8F8F2">, </span><span style="color: #AE81FF">1</span><span style="color: #F8F8F2">, </span><span style="color: #AE81FF">1</span><span style="color: #F8F8F2">))</span></span>
<span class="line"></span>
<span class="line"><span style="color: #88846F"># Display the combined plot</span></span>
<span class="line"><span style="color: #66D9EF">print</span><span style="color: #F8F8F2">(combined_plot)</span></span></code></pre></div>



<p id="674e">In this example, we first create a list of data frames, one for each unique number of cylinders in the <code>mtcars</code> dataset. Then, we define a custom function <code>create_ggplot()</code> to create a ggplot for a given data frame. The function creates a scatterplot of miles per gallon (mpg) versus horsepower (hp), with a title that reflects the number of cylinders.</p>



<p id="1d4e">Finally, we use <code>purrr</code>‘s <code>map()</code> function to apply the custom function to each data frame in the list, resulting in a list of ggplots. We use a for loop to display each ggplot.</p>



<p id="4483">The plot we get can be seen below:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="720" height="663" loading="lazy" src="https://analyticadss.com/wp-content/uploads/2023/04/1_0zvCrChg56Sq3kBk3neGSg.webp" alt="" class="wp-image-6139" srcset="https://analyticadss.com/wp-content/uploads/2023/04/1_0zvCrChg56Sq3kBk3neGSg.webp 720w, https://analyticadss.com/wp-content/uploads/2023/04/1_0zvCrChg56Sq3kBk3neGSg-500x460.webp 500w, https://analyticadss.com/wp-content/uploads/2023/04/1_0zvCrChg56Sq3kBk3neGSg-150x138.webp 150w" sizes="auto, (max-width: 720px) 100vw, 720px" /></figure>
</div>


<p id="aa70">In this example, we’ve made some changes to the <code>create_ggplot()</code> function to improve the aesthetics of the plots:</p>



<ol class="wp-block-list">
<li>We use <code>geom_point(aes(color = factor(gear)), size = 3)</code> to color the points by the number of gears and increase their size.</li>



<li>We apply <code>theme_minimal()</code> to use a minimalistic theme for the plots.</li>



<li>We remove the legend title using <code>theme(legend.title = element_blank())</code>.</li>



<li>We rename the color scale to “Gears” using <code>scale_color_discrete(name = "Gears")</code>.</li>
</ol>



<p id="f475">Finally, we use the <code>plot_grid()</code> function from the <code>cowplot</code> package to combine the ggplots in the <code>ggplot_list</code> into a single plot with one column and display the combined plot.</p>



<p id="2900">These examples showcase how the <code>purrr</code> package can help you write more efficient and readable code, making your data analysis workflows more robust and maintainable. By incorporating <code>purrr</code> into your R projects, you can take full advantage of functional programming techniques and harness their power to solve complex problems.</p>



<hr class="wp-block-separator has-alpha-channel-opacity is-style-dots"/>



<h2 class="wp-block-heading has-medium-font-size" id="5467">Tips and Best Practices for Using purrr</h2>



<p id="e68e">In this final section, we will share some tips and best practices for using the <code>purrr</code> package in your R projects. These recommendations will help you write more efficient, readable, and maintainable code.</p>



<p id="6bbd"><strong>1. Use anonymous functions when appropriate</strong></p>



<p id="5346">When using <code>map()</code> functions, you can create anonymous functions using the <code>~</code> notation, which allows for concise and readable code. However, if the function becomes too complex or is used multiple times, consider defining it as a separate named function for better code organization and readability.</p>



<p id="aafb"><strong>2. Leverage the power of function composition</strong></p>



<p id="d747">The <code>compose()</code> function allows you to create new functions by combining existing ones. This technique promotes code reusability and makes it easier to build complex functionality by breaking it down into simpler, more manageable parts.</p>



<p id="76d8"><strong>3. Handle errors gracefully</strong></p>



<p id="21ec">When applying a function to a list or vector, use functions like <code>safely()</code>, <code>quietly()</code>, and <code>possibly()</code> to handle errors gracefully without stopping the execution of your code. This approach ensures that your code remains robust and can handle unexpected input values.</p>



<p id="97a5"><strong>4. Know when to use purrr vs. base R or dplyr</strong></p>



<p id="aac3">While <code>purrr</code> provides a powerful and flexible way to manipulate data, there are cases where base R or <code>dplyr</code> functions may be more appropriate or efficient. For example, if you need to perform simple operations on a data frame, consider using <code>dplyr</code> functions like <code>mutate()</code> or <code>summarize()</code>. Evaluate the needs of your specific task and choose the best tool for the job.</p>



<p id="d5c9"><strong>5. Familiarize yourself with the purrr documentation</strong></p>



<p id="57fa">The <code>purrr</code> package has a wealth of functions and features that can help you streamline your code and solve complex problems. Make sure to consult the official documentation (<a href="https://purrr.tidyverse.org/" rel="noreferrer noopener" target="_blank">https://purrr.tidyverse.org/</a>) to explore its full capabilities and discover new techniques.</p>



<p id="eac3">By following these tips and best practices, you can fully leverage the power of the <code>purrr</code> package in your R projects, making your code more efficient, readable, and maintainable. Embrace the functional programming paradigm and use <code>purrr</code> to solve real-world data analysis challenges with ease.</p>



<hr class="wp-block-separator has-alpha-channel-opacity is-style-dots"/>



<h1 class="wp-block-heading" id="c363">Wrapping up</h1>



<p id="6914">Throughout this article, we’ve delved into the capabilities and adaptability of R’s <code>purrr</code> package in the realm of functional programming and data handling. Spanning from foundational functional programming principles to the pivotal role of the map() function suite, all the way to intricate subjects like engaging nested data sets and adept error management.</p>



<p id="75dd">Using real-world scenarios, we’ve showcased how <code>purrr</code> can be instrumental in de-complicating daunting tasks, optimizing your scripts, and enhancing its legibility and sustainability. Incorporating <code>purrr</code> into your R utilities ensures a smoother journey through data manipulation and analytical hurdles.</p>



<p id="78e2">As you venture further into the depths of the <code>purrr</code> package, bear in mind that mastery comes with repetition. Embrace exploration, and endeavor to ingeniously apply <code>purrr</code> functionalities in your endeavors. With perseverance, you’ll cultivate a profound grasp of its intricacies, propelling you towards proficient data management in R.</p>



<p id="15ba">Happy coding!</p>



<p id="b396"><strong>Further Reading and Exploration:</strong></p>



<p id="79d8">For those eager to expand their expertise on <code>purrr</code> and R’s functional programming, consider the following treasure trove of resources:</p>



<ol class="wp-block-list">
<li><code>purrr’s</code> Official Guide: As a logical first step, the <code>purrr</code> package’s official documentation provides a thorough overview of all it offers. Dive into the nuances at <code>purrr’s</code><a href="https://purrr.tidyverse.org/" rel="noreferrer noopener" target="_blank"> official site</a>.</li>



<li>R for Data Science: A masterpiece penned by Hadley Wickham and Garrett Grolemund, this digital tome offers an exhaustive look into R’s role in data science. Notably, it features a segment dedicated to <code>purrr’s</code> prowess in functional programming. Grab your copy <a href="https://r4ds.had.co.nz/" rel="noreferrer noopener" target="_blank">here</a>.</li>



<li>Advanced R: A deeper dive by Hadley Wickham, “Advanced R” ventures into the more intricate aspects of R, shedding light on advanced functional programming paradigms. Embark on this advanced journey <a href="https://adv-r.hadley.nz/" rel="noreferrer noopener" target="_blank">here</a>.</li>



<li>RStudio’s Vibrant Community: Seeking advice, hoping to discuss new findings, or simply aiming to network? The RStudio community is a hub of enthusiasts, experts, and curious minds. Engage with like-minded individuals <a href="https://community.rstudio.com/" rel="noreferrer noopener" target="_blank">right here</a>.</li>
</ol>



<p id="238c">Harnessing these resources and proactively mingling with the wider R circle will undoubtedly refine your prowess with both the <code>purrr</code> package and R’s functional programming realm. Continue your journey of discovery, trial, and collaborative learning to blossom as an adept data scientist and R aficionado.</p>
<p>The post <a href="https://analyticadss.com/unleash-the-power-of-functional-programming-in-r-with-the-purrr-package/">Unleash the Power of Functional Programming in R with the purrr Package</a> appeared first on <a href="https://analyticadss.com">Analytica Data Science Solutions</a>.</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
