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 apply(), lapply(), vapply(), and 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 predetermined 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 – A vector or list on which you want to apply a function.
  • FUN -The function should be applied to each element of…
  • ... – Optional. Arguments to FUN (Function)

Apply Function to Vector in R

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 vector in R. In the returned list, each element is the result of applying FUN to the corresponding component of X.

Let’s use the R lapply() function to convert the elements of the vector to lowercase. Since lapply() returns 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

Apply Custom Function to Vector in R

Now let’s create a custom function in R and call it from the 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. 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 the 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.

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(), apply(), 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 returns 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