Get Started

lapply and anonymous functions

Writing your own functions and then using them inside lapply() is quite an accomplishment! But defining functions to use them only once is kind of overkill, isn't it? That's why you can use so-called anonymous functions in R.

Previously, you learned that functions in R are objects in their own right. This means that they aren't automatically bound to a name. When you create a function, you can use the assignment operator to give the function a name. It's perfectly possible, however, to not give the function a name. This is called an anonymous function:

# Named function
triple <- function(x) { 3 * x }

# Anonymous function with same implementation
function(x) { 3 * x }

# Use anonymous function inside lapply()
lapply(list(1,2,3), function(x) { 3 * x })

split_low is defined for you.

This is a part of the course

“Intermediate R”

View Course

Exercise instructions

  • Transform the first call of lapply() such that it uses an anonymous function that does the same thing.
  • In a similar fashion, convert the second call of lapply to use an anonymous version of the select_second() function.
  • Remove both the definitions of select_first() and select_second(), as they are no longer useful.

Hands-on interactive exercise

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

# split_low has been created for you
split_low

# Transform: use anonymous function inside lapply
select_first <- function(x) {
  x[1]
}
names <- lapply(split_low, select_first)

# Transform: use anonymous function inside lapply
select_second <- function(x) {
  x[2]
}
years <- lapply(split_low, select_second)

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 functions
Exercise 5: Use lapply with additional argumentsExercise 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