Explained apply Functions in R with Examples (2024)

What is an apply function in R and explain how to use apply functions with examples? R Programming provides several applied collections that include apply(), lapply(), vapply(), sapply() and many more functions, all these collections are used to call a function for each element of the R sequence objects like DataFrame, Matrix, Vector, and List.

Advertisem*nts

By applying functions, we can explicitly avoid using looping control structures in R. These collections can be used with an input object list, matrix, data.frame, and array.

In this article, I will explain all apply functions collection, their syntaxes, and usage with examples. Also, how we can use these apply functions as a substitute for the looping in R.

  • R apply() Function with Examples
  • R lapply() Function with Examples
  • R vapply() Function with Examples
  • R apply() Function with Example
  • R replicate() Function with Examples
  • R simplify2array() Function with Examples

1. What are applied Functions?

apply function in R are used to apply base functions or custom functions to each row or column of the DataFrame, each element of the vector or list, etc. Traditionally to apply anything to each element of the object, we use for loop in R which is not the most efficient way. The apply collection can be viewed as a substitute for the loop.

  • lapply– Returns a list of the same length asX. It can take a vector as input and always return a list
  • sapply– User-friendly version and wrapper oflapply. This by default returns a vector, matrix, or, an array.
  • vapply– Same as sapply, but has a pre-specified type of return value.
  • replicateis a wrapper for the common use ofsapplyfor repeated evaluation of an expression (which will usually involve random number generation).
  • simplify2array()is the utility called fromsapply()whensimplifyis not false and is similarly called from mapply.

2. Quick Examples of apply Functions in R

Let’s see the most used apply functions in R.

# Syntax of several apply functionssapply(X, FUN, ..., simplify = TRUE, USE.NAMES = TRUE)vapply(X, FUN, FUN.VALUE, ..., USE.NAMES = TRUE)replicate(n, expr, simplify = "array")simplify2array(x, higher = TRUE, except = c(0L, 1L))

Below are details about some arguments that I will be using here.

  • X – A vector or list.
  • FUN – The function that will be applied to each element of X.
  • ... – Optional. Additional parameters are to be passed to the FUN (Function).

3. apply() Function in R

The apply() function in R is a base function that takes Data.frame or Matrix as an input and returns a vector, list, or array. All other apply collections are wrappers on top of the apply().

3.1 Syntax of apply()

# apply() Syntaxapply(X, MARGIN, FUN)
  • X – A vector or list where you want to apply a function.
  • MARGIN – An integer specifying which margins to retain.
  • FUN – the function to be applied to each element ofX

3.2 Example of apply()

4. lapply() Function

To apply a function to every element of a vector in R use the lapply() function. It takes a vector or list as input and always returns a list. You can use unlist() to convert the list to a vector in R. In the returned list, each element is the result of applyingFUNto the corresponding element ofX.

4.1 Syntax of lapply()

lapply(X, FUN, ...)

4.2 Apply lapply() with R Base Function

Let’s use the R lapply() function to translate the items of the vector to lowercase. Since lapply() generates the list, our result will be in a list containing lowercase strings.

# Using lapply() with FUNvec <- c('JAVA','R','PYTHON','PHP')print(vec)# Apply function to vectorres <- lapply(vec, FUN=tolower)res

Yields below output.

Explained apply Functions in R with Examples (1)

4.3 Apply Custom Function to Vector in R

You can create a custom function in R and implement it using the lapply() function by specifying the function name to the FUN argument. Here, the getLang() is called for every single element of the vector, and the function getLang() splits the string based on the specified delimiter '_' and generates the starting part of the string.

# custom function# function to split and get the first partgetLang <- function(str) { return (unlist(strsplit(str,'_'))[1])}# create vectorvec <- c('JAVA_LANG','R_LANG','PYTHON_LANG','PHP_LANG')vec# apply functionres <- lapply(vec, FUN=getLang)res

Yields below output.

Explained apply Functions in R with Examples (2)

4.4 Apply Function with Parameters

Let’s apply the function with arguments to Vector. In the previous example, I hardcoded the '_' the delimiter in getLang() that I used to split the string using the strsplit() function.

In the following example, I pass the delimiter as an argument to the getLang() function, which is then used in strsplit(). This approach allows for changing the delimiter dynamically at runtime through a function call.

# function to split and get the first part# Pass as an argument if you wanted to use different delimiter to splitgetLang <- function(str="", delimiter=',') { return (unlist(strsplit(str,delimiter))[1])}# create vectorvec <- c('JAVA_LANG','R_LANG','PYTHON_LANG','PHP_LANG')vec# apply functionres <- lapply(vec, FUN=getLang,delimiter='_')res

Yields the same output as above.

5. sapply() Function

5.1 Syntax of sapply()

5.2 Example of sapply()

6. vapply() Function

6.1 Syntax of vapply()

6.2 Example of vapply()

7. mapply() Function

Conclusion

In this article, you have learned how to apply a function to each element of a Vector in R. You can use functions like apply(), lapply(), vapply(), sapply() etc. lapply() returns a list of the same length asX. It can take a vector as input and always return a list. sapply() is a user-friendly version and wrapper oflapply. This by default generates a vector, matrix, or, an array. vapply()is the same as sapply, but has a pre-specified type of return value.

You can find the complete example at GitHub R Examples

Related Articles

  • R FUN Usage with Examples
  • names() Function in R with Examples
  • Dollar in R
  • Pipe in R with Examples
  • Usage of %in% Operator in R
  • Remove Character From String in R
  • Filter in sparklyr | R Interface to Spark
  • Sparklyr join explained with examples
  • Sparklyr Sort DataFrame with Examples
  • Explained apply Functions in R with Examples
  • R Count Frequency of All Unique Values in Vector
Explained apply Functions in R with Examples (2024)

References

Top Articles
Latest Posts
Article information

Author: Annamae Dooley

Last Updated:

Views: 6348

Rating: 4.4 / 5 (65 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Annamae Dooley

Birthday: 2001-07-26

Address: 9687 Tambra Meadow, Bradleyhaven, TN 53219

Phone: +9316045904039

Job: Future Coordinator

Hobby: Archery, Couponing, Poi, Kite flying, Knitting, Rappelling, Baseball

Introduction: My name is Annamae Dooley, I am a witty, quaint, lovely, clever, rich, sparkling, powerful person who loves writing and wants to share my knowledge and understanding with you.