R’s sapply() Function With Examples


Hi there. This page is about R’s sapply function. The sapply function is a neat function where values in a dataframe column can be used as inputs for functions inside sapply. This concept will make more sense with the examples below.


Examples Of sapply()


Example One


In the first example, I create a table of values for a simple quadratic function y = x^2. The x-values are natural numbers from 1 to 10 and is in a dataframe.



A R function for the y = x^2 quadratic equation is made which will be used for sapply() later.


Once the function is created, this function can be used in the sapply function. I apply this function to the x column such that the x-values are inputs in the x_squared function.



A natural extension is to use R’s ggplot2 package to generate a plot and function sketch.



Example Two (Anonymous Function)

In the sapply() function, you can create a function as an argument instead of defining a function outside of sapply(). Refer to the example below where the function is the square root of x (y = \sqrt(x)).


Like in the first example, you can use ggplot2 for plotting.




Example Three

R’s sapply() does not necessarily have to be used for math. This example looks an numeric grades and gives a pass/fail outcome with the passFail function and sapply().

(The passing grade here is 60 instead of the regular 50.)



Example Four

This example features assigning a weight condition given a BMI score. I have created a (fake and random) list of BMI numbers in R.

I have used this website as a reference for BMI categories.



To assign weight conditions given numeric bmis, an if-elseif-else format is needed in the function for sapply().





Leave a Reply