sapply with your own function
Like lapply()
, sapply()
allows you to use self-defined functions and apply them over a vector or a list:
sapply(X, FUN, ...)
Here, FUN
can be one of R's built-in functions, but it can also be a function you wrote. This self-written function can be defined before hand, or can be inserted directly as an anonymous function.
This is a part of the course
“Intermediate R”
Exercise instructions
- Finish the definition of
extremes_avg()
: it takes a vector of temperatures and calculates the average of the minimum and maximum temperatures of the vector. - Next, use this function inside
sapply()
to apply it over the vectors insidetemp
. - Use the same function over
temp
withlapply()
and see how the outputs differ.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# temp is already defined in the workspace
# Finish function definition of extremes_avg
extremes_avg <- function(___) {
( min(x) + ___ ) / 2
}
# Apply extremes_avg() over temp using sapply()
# Apply extremes_avg() over temp using lapply()
This exercise is part of the course
Intermediate R
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 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 vapplyWhat is DataCamp?
Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.