Built with Tutify.io

    AIStudyLabs

    Explained apply Functions in R with Examples

    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 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.

    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.

    <a id="apply-functions-in-r"></a>

    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.

    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.

    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() Syntax
    apply(X, MARGIN, FUN)
    

    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 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 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 FUN
    vec <- c('JAVA','R','PYTHON','PHP')
    print(vec)
    
    # Apply function to vector
    res <- lapply(vec, FUN=tolower)
    res
    

    Yields below output.

    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 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.

    <a id="h-4-4-apply-function-with-parameters"></a>

    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 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()

    <a id="h-6-vapply-function"></a>

    6. vapply() Function

    <a id="h-6-1-syntax-of-vapply"></a>

    6.1 Syntax of vapply()

    <a id="h-6-2-example-of-vapply"></a>

    6.2 Example of vapply()

    7. mapply() Function

    <a id="h-conclusion"></a>

    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(), tapply(), sapply() etc. lapply()  returns a list of the same length as X. It can take a vector as input and always return a list. sapply() is a user-friendly version and wrapper of lapply. 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