You are currently viewing R Apply Function to Vector

How to apply a function to each element of R Vector? R Programming provides several functions to apply or call a function to each element of a vector, for example, functions like apply(), lapply(), vapply(), sapply().

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

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

2. Functions to Apply to Vector

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

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

# Syntax of several apply functions
lapply(X, FUN, ...)

sapply(X, FUN, ..., simplify = TRUE, USE.NAMES = TRUE)

vapply(X, FUN, FUN.VALUE, ..., USE.NAMES = TRUE)

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 to Vector in R

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.

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

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

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