<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/those-other-apply-functions/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://theautomatic.net/2018/11/13/those-other-apply-functions/"> R – Open Source Automation</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p><img alt="r vapply eapply rapply" src="https://i1.wp.com/theautomatic.net/wp-content/uploads/2018/11/r-vapply-eapply-rapply.jpeg?w=640" data-recalc-dims="1"></p>
<p>So you know <a href="https://www.r-bloggers.com/using-apply-sapply-lapply-in-r/">lapply, sapply, and apply</a>…but…what about <em>rapply</em>, <em>vapply</em>, or <em>eapply</em>? These are generally a little less known as far as the apply family of functions in R go, so this post will explore how they work.</p>
<h2><strong>rapply</strong></h2>
<p>Let’s start with <em>rapply</em>. This function has a couple of different purposes. One is to recursively apply a function to a list. We’ll get to that in a moment. The other use of <em>rapply</em> is to a apply a function to only those elements in a list (or columns in a data frame) that belong to a specified class. For example, let’s say we have a data frame with a mix of categorical and numeric variables, but we want to evaluate a function <em>only</em> on the numeric variables.</p>
<h4><strong>Use rapply to apply a function to elements of a given class</strong></h4>
<p>Using the traditional iris dataset, we can run the one-liner below to get the mean of each numeric column. This works almost exactly like <em>sapply</em>, except we add an extra parameter, <em>class</em>, to specify we only want to apply our function to the numeric columns in iris.</p>
<pre>

# apply to only numeric variables
rapply(iris, mean, class = &quot;numeric&quot;)

rapply(iris, max, class = &quot;numeric&quot;)

rapply(iris, min, class = &quot;numeric&quot;)

# or apply to only factor columns
rapply(iris, summary, class = &quot;factor&quot;)


</pre>
<p>If you’re unsure of the class of a particular column in a data frame, <em>df</em>, just run the following to get the clases of each variable.</p>
<pre>

sapply(df, class)

</pre>
<p>The other purpose of <em>rapply</em> is to apply a function recursively to a list.</p>
<pre>

temp &lt;- list(a = c(1, 2, 3), 
             b = list(a = c(4, 5, 6), b = c(7, 8, 9)),
             c = list(a = c(10, 11, 12), b = c(13, 14, 15)))


rapply(temp, sum)


</pre>
<p><img alt="rapply nested list" src="https://i1.wp.com/theautomatic.net/wp-content/uploads/2018/11/nested_list_rapply.png?w=640" data-recalc-dims="1"></p>
<p>Running <em>rapply</em> here will recursively sum the elements of each vector in each list and sub-list of <em>temp</em>.</p>
<p><img alt="rapply sum" src="https://i1.wp.com/theautomatic.net/wp-content/uploads/2018/11/rapply_sum.png?w=640" data-recalc-dims="1"></p>
<p><em>rapply</em>, similar to <em>sapply</em>, has an optional parameter <em>how</em>, which specifies how the output should be returned. So in the above example, if we wanted the output to be returned as a list instead of a vector, we could do this:</p>
<pre>

rapply(temp, sum, how = &quot;list&quot;)

</pre>
<p>Also, if our nested list contained mixed data types, we could specify applying a function to only a specific type:</p>
<pre>

rapply(temp, sum, how = &quot;list&quot;, class = &quot;numeric&quot;)

</pre>
<h2><strong>vapply</strong></h2>
<p><em>vapply</em> works similarly to <em>sapply</em>, except that it requires an extra parameter specifying the type of the expected return value. This extra parameter is useful in coding because it can help ensure silent errors don’t cause issues for you.</p>
<p>For example, suppose we have the following list of mixed data types:</p>
<pre>

sample_list &lt;- list(10, 20, 30, &quot;some_string&quot;)

</pre>
<p>Now if we run the below code with <em>sapply</em>, we get a vector of characters, which is not exactly what we want. For instance, if we didn’t know our list had mixed data types, and we ran our function to the get the max of each element in the list, then R doesn’t return an error here. Instead, it silently converts the output to a character vector.</p>
<pre>

sapply(sample_list, max)

</pre>
<p><img alt="sapply vs. vapply" src="https://i0.wp.com/theautomatic.net/wp-content/uploads/2018/11/sapply.png?w=640" data-recalc-dims="1"></p>
<p>However, we can catch this error using <em>vapply</em>.</p>
<pre>

vapply(sample_list, max, numeric(1))

</pre>
<p>This third parameter, <em>numeric(1)</em> specifies that we want the output returned by <em>vapply</em> to be numeric. This means if an issue occurs in returning a numeric result, <em>vapply</em> will result in an error, rather than trying to coerce the result to a different data type. This could allow you to investigate why a character is in the list, for example.</p>
<p><img alt="vapply error" src="https://i1.wp.com/theautomatic.net/wp-content/uploads/2018/11/vapply-error.png?w=640" data-recalc-dims="1"></p>
<p><em>vapply’s</em> ability to catch errors based off data types makes it useful for running R code in production <a href="http://theautomatic.net/2018/10/31/how-to-run-r-from-the-task-scheduler/">or as a scheduled task</a> as an extra measure to guard against type issues.</p>
<h2><strong>eapply</strong></h2>
<p><em>eapply</em> applies a function to every named element in an environment. This requires a little knowledge about <a rel="nofollow" href="https://www.r-bloggers.com/environments-in-r/" target="_blank">how environments work in R</a>. It works pretty similarly to <em>lapply</em> in that it also returns a list as output. The input to <em>eapply</em>, however, must be an environment, whereas <em>lapply</em> can take a variety of objects as inputs.</p>
<p>Here’s an example:</p>
<pre>

# create a new environment
e &lt;- new.env()

e$a &lt;- 10
e$b &lt;- 20
e$c &lt;- 30

# multiply every element in the environment by 2
new_e &lt;- eapply(e, function(x) x * 2)


</pre>
<p>In the above example, we create a list from the initiated environment, <em>e</em>, and then double the value of each element.</p>
<p>Here’s another example, using the environment within a function:</p>
<pre>

sample_func &lt;- function()
{

   df1 &lt;- data.frame(a = c(1, 2, 3, 4), b = c(5, 6, 7, 8))
   df2 &lt;- data.frame(a = c(1, 2, 3, 4, 5), b = c(5, 6, 7, 8, 9))
   df3 &lt;- data.frame(a = c(1, 2, 3, 4, 5, 6), b = c(5, 6, 7, 8, 9, 10)) 

   eapply(environment(), nrow)

}

sample_func()

</pre>
<p>Above, calling <em>sample_func</em> will return a list of the number of rows for each respective data frame defined within the function’s environment:</p>
<p><img alt="eapply result" src="https://i0.wp.com/theautomatic.net/wp-content/uploads/2018/11/eapply_result.png?w=640" data-recalc-dims="1"></p>
<p><em>eapply</em> can also be called with the parameter <strong>USE.NAMES = FALSE</strong>, which will return an unnamed list.</p>
<pre>

eapply(environment(), nrow, USE.NAMES = FALSE)

</pre>
<p>One other difference versus <em>lapply</em> is that <em>eapply</em> can take an optional Boolean parameter called <em>all.names</em> that specifies if the function input should be applied to just the visible elements of the environment, or to all objects. Here’s an example to illustrate:</p>
<pre>

e &lt;- new.env()
e$.test &lt;- 100
e$other_test &lt;- 64

</pre>
<p>Here, we defined an environment with one object called <em>.test</em> and one called <em>other_test</em>. Next, if we run this:</p>
<pre>

eapply(e, sqrt)

</pre>
<p>we’ll get back a list with one element – 8. As in, <em>eapply</em> is only applying the <em>sqrt</em> function to the object named <em>other_test</em> in <em>e</em> because it is not a hidden object. Names that begin with a dot (hidden objects) are excluded from the function’s application. To apply the function to every object in the environment, we need to set the parameter <strong>all.names = TRUE</strong>.</p>
<p><img alt="eapply all.names parameter" src="https://i2.wp.com/theautomatic.net/wp-content/uploads/2018/11/eapply_all_names.png?w=640" data-recalc-dims="1"></p>
<p>Please check out other R articles of mine here: <a rel="nofollow" href="http://theautomatic.net/category/r/" target="_blank">http://theautomatic.net/category/r/</a>.</p>
<p>The post <a rel="nofollow" href="http://theautomatic.net/2018/11/13/those-other-apply-functions/" target="_blank">Those “other” apply functions…</a> appeared first on <a rel="nofollow" href="http://theautomatic.net/" target="_blank">Open Source Automation</a>.</p>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://theautomatic.net/2018/11/13/those-other-apply-functions/"> R – Open Source Automation</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/THvC_AlQwaU" height="1"></a></div>