You are currently viewing Explained apply Functions in R with Examples

What is an apply function in R and explain how to use apply functions with examples? R Programming provides several apply collections that includes 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.

By using apply 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() Funtion with Examples
  • R lapply() Function with Examples
  • R apply() 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 apply 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 as X. It can take vector as input and always return a list
  • sapply – User-friendly version and wrapper of lapply. This by default return a vector, matrix or, an array.
  • vapply – Same as sapply, but has a pre-specified type of return value.
  • replicate is a wrapper for the common use of sapply for repeated evaluation of an expression (which will usually involve random number generation).
  • simplify2array() is the utility called from sapply() when simplify is not false and is similarly called from <a href="https://stat.ethz.ch/R-manual/R-devel/library/base/help/mapply.html">mapply</a>().

2. Quick Examples of apply Functions in R

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


# Syntax of several apply functions

sapply(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 where you wanted to apply a function.
  • FUN – the function to be applied to each element of X
  • ... – Optional. Arguments to 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 actually wrappers on top of the apply().

3.1 Syntax of apply()


# apply() Syntax
apply(X, MARGIN, FUN)
  • X – A vector or list where you wanted to apply a function.
  • MARGIN
  • FUN – the function to be applied to each element of X

3.2 Example of apply()



4. lapply() Function

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

4.1 Syntax of lapply()


lapply(X, FUN, ...)

4.2 Apply lapply() with R Base Function

Let’s use the R lapply() function to convert the elements of the vector to lowercase. Since lapply() return the list, our result will be in a list with lowercase strings.


# Using lapply() with FUN
vec <- c('JAVA','R','PYTHON','PHP')
print(vec)

# Apply function to vector
res <- lapply(vec, FUN=tolower)
res

Yields below output.

R Apply Function Vector

4.3 Apply Custom Function to Vector in R

Now let’s create a custom function in R and call it from lapply() function by passing the function name to the FUN argument. Here, the getLang() function is called for each element of the vector and the function getLang() splits the string by delimiter ‘_’ and returns the first part of the string.


# custom function
# function to split and get the first part
getLang <- function(str) { 
  return (unlist(strsplit(str,'_'))[1])
}

# create vector
vec <- c('JAVA_LANG','R_LANG','PYTHON_LANG','PHP_LANG')
vec

# apply function
res <- lapply(vec, FUN=getLang)
res

Yields below output.

4.4 Apply Function with Arguments

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

In the below example I am taking delimiter as an argument to the function getLang() and using it on strsplit() so, now I have the flexibility of changing the delimiter at runtime with a function call.


# function to split and get the first part
# Pass as an argument if you wanted to use different delimiter to split
getLang <- function(str="", delimiter=',') { 
  return (unlist(strsplit(str,delimiter))[1])
}

# create vector
vec <- c('JAVA_LANG','R_LANG','PYTHON_LANG','PHP_LANG')
vec

# apply function
res <- 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() e.t.c. lapply()  returns a list of the same length as X. It can take vector as input and always return a list. sapply() is a user-friendly version and wrapper of lapply. This by default return a vector, matrix or, an array. vapply() is same as sapply, but has a pre-specified type of return value.

You can find the complete example at GitHub R Examples

Related Articles

Naveen Nelamali

Naveen Nelamali (NNK) is a Data Engineer with 20+ years of experience in transforming data into actionable insights. Over the years, He has honed his expertise in designing, implementing, and maintaining data pipelines with frameworks like Apache Spark, PySpark, Pandas, R, Hive and Machine Learning. Naveen journey in the field of data engineering has been a continuous learning, innovation, and a strong commitment to data integrity. In this blog, he shares his experiences with the data as he come across. Follow Naveen @ LinkedIn and Medium