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()