Foldable operations (I)
An operation that gives the same answer whether you apply it to an entire data set or to chunks of a data set and then on the results on the chunks is sometimes called foldable. The max()
and min()
operations are an example of this.
Here, we have defined a foldable version of the range()
function that takes either a vector or list of vectors.
Verify that the function works by testing it on the mortgage data set.
This exercise is part of the course
Scalable Data Processing in R
Exercise instructions
- Verify that
foldable_range()
works on the"record_number"
column of themort
data set.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
foldable_range <- function(x) {
if (is.list(x)) {
# If x is a list then reduce it by the min and max of each element in the list
c(Reduce(min, x), Reduce(max, x))
} else {
# Otherwise, assume it's a vector and find its range
range(x)
}
}
# Verify that foldable_range() works on the record_number column
___