You are currently viewing R Apply Function to Vector

How to apply a function to each element of R Vector? R Programming offers 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.

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='_')

Functions to Apply to Vector

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

  • lapply – Generates a list of the same length as X, capable of accepting vectors as input and consistently producing a list as output.
  • sapply – serves as a user-friendly version of lapply, naturally providing a vector, matrix, or array.
  • vapply – vapply functions similarly to sapply but allows for a predefined type of return value.

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

  • X – Is the vector or list on which the function will be applied.
  • FUN -The function should be applied to each element of…
  • ... – Optional. Arguments to FUN (Function)

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.

R Apply Function Vector

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.

r apply function vector

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.

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