Built with Tutify.io

    AIStudyLabs

    R Apply Function to Vector

    R Apply Function to Vector

    How to apply a function to each element of R Vector? R Programmingoffers a variety of functions for applying or invoking a function on each element within a vector. Examples of these functions include lapply(), vapply(), and the sapply().

    In this article, I will explain how to apply an existing R base function to a vector, create a custom function, and apply it to every element of the R vector.

    <a id="h-quick-examples"></a>

    Quick Examples

    
    # Using FUN with lapply()
    vec <- c('JAVA','R','PYTHON','PHP')
    res <- lapply(vec, FUN=tolower)
    
    # 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')
    
    # apply function
    res <- lapply(vec, FUN=getLang)
    
    # function to split and get the first part
    getLang <- function(str="", delimiter=',') { 
      return (unlist(strsplit(str,delimiter))[1])
    }
    
    # create vector
    vec <- c('JAVA_LANG','R_LANG','PYTHON_LANG','PHP_LANG')
    
    # apply function
    res <- lapply(vec, FUN=getLang,delimiter='_')
    

    <a id="h-functions-to-apply-to-vector"></a>

    Functions to Apply to Vector

    Let's see functions with their syntaxes used to apply a function to a vector.

    
    # Syntax of several apply functions
    lapply(X, FUN, ...)
    
    sapply(X, FUN, ..., simplify = TRUE, USE.NAMES = TRUE)
    
    vapply(X, FUN, FUN.VALUE, ..., USE.NAMES = TRUE)
    

    Following is the information about the arguments of the above functions.

    <a id="h-apply-function-to-vector-in-r"></a>

    Apply Function to Vector in R

    lapply() is a function in R that applies a given function (specified by the FUN argument) to each element of a list or vector. It generates a list where each element represents the outcome of applying the tolower() function to each element within the given vector.

    We will use the R lapply() method to transform the vector elements into lowercase. Given that lapply() produces a list, our output will consist of lowercase strings within a list.

    If you want to convert from list to vector in R you can use unlist() function.

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

    <a id="h-apply-custom-function-to-vector-in-r"></a>

    Apply Custom Function to Vector in R

    Let's create a custom function in R and invoke it using the lapply() function, passing the function name to the FUN argument. In this case, the getLang() function is applied to each element of the vector. The getLang() function splits the string by the 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.

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

    Apply Function with Arguments

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

    In the example below, the getLang() function takes the delimiter as an argument and uses it with strsplit(). This allows for the flexibility to change 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.

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

    Conclusion

    In this article, you learned how to apply a function to each element of a Vector in R using various functions such as apply(), lapply(), vapply(), and sapply(). The lapply() function returns a list of the same length as the input and can take a vector as input, always returning a list. The sapply() function is a more user-friendly version and wrapper of lapply, typically returning a vector, matrix, or array by default. The vapply() function is similar to sapply, but requires a pre-specified type for the return value.

    You can find the complete example at GitHub R Examples.

    Related Articles