How to use sapply
You can use sapply()
similar to how you used lapply()
. The first argument of sapply()
is the list or vector X
over which you want to apply a function, FUN
. Potential additional arguments to this function are specified afterwards (...
):
sapply(X, FUN, ...)
In the next couple of exercises, you'll be working with the variable temp
, that contains temperature measurements for 7 days. temp
is a list of length 7, where each element is a vector of length 5, representing 5 measurements on a given day. This variable has already been defined in the workspace: type str(temp)
to see its structure.
This is a part of the course
“Intermediate R”
Exercise instructions
- Use
lapply()
to calculate the minimum (built-in functionmin()
) of the temperature measurements for every day. - Do the same thing but this time with
sapply()
. See how the output differs. - Use
lapply()
to compute the the maximum (max()
) temperature for each day. - Again, use
sapply()
to solve the same question and see howlapply()
andsapply()
differ.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# temp has already been defined in the workspace
# Use lapply() to find each day's minimum temperature
# Use sapply() to find each day's minimum temperature
# Use lapply() to find each day's maximum temperature
# Use sapply() to find each day's maximum temperature