Get Started

Use lapply with additional arguments

In the video, the triple() function was transformed to the multiply() function to allow for a more generic approach. lapply() provides a way to handle functions that require more than one argument, such as the multiply() function:

multiply <- function(x, factor) {
  x * factor
}
lapply(list(1,2,3), multiply, factor = 3)

On the right we've included a generic version of the select functions that you've coded earlier: select_el(). It takes a vector as its first argument, and an index as its second argument. It returns the vector's element at the specified index.

This is a part of the course

“Intermediate R”

View Course

Exercise instructions

Use lapply() twice to call select_el() over all elements in split_low: once with the index equal to 1 and a second time with the index equal to 2. Assign the result to names and years, respectively.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Definition of split_low
pioneers <- c("GAUSS:1777", "BAYES:1702", "PASCAL:1623", "PEARSON:1857")
split <- strsplit(pioneers, split = ":")
split_low <- lapply(split, tolower)

# Generic select function
select_el <- function(x, index) {
  x[index]
}

# Use lapply() twice on split_low: names and years

This exercise is part of the course

Intermediate R

BeginnerSkill Level
4.5+
131 reviews

Continue your journey to becoming an R ninja by learning about conditional statements, loops, and vector functions.

Whenever you're using a for loop, you may want to revise your code to see whether you can use the lapply function instead. Learn all about this intuitive way of applying a function over a list or a vector, and how to use its variants, sapply and vapply.

Exercise 1: lapplyExercise 2: Use lapply with a built-in R functionExercise 3: Use lapply with your own functionExercise 4: lapply and anonymous functionsExercise 5: Use lapply with additional arguments
Exercise 6: Apply functions that return NULLExercise 7: sapplyExercise 8: How to use sapplyExercise 9: sapply with your own functionExercise 10: sapply with function returning vectorExercise 11: sapply can't simplify, now what?Exercise 12: sapply with functions that return NULLExercise 13: Reverse engineering sapplyExercise 14: vapplyExercise 15: Use vapplyExercise 16: Use vapply (2)Exercise 17: From sapply to vapply

What is DataCamp?

Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.

Start Learning for Free