R Functionals
Functionals are functions that take a function as an argument and run it over values. Map(), Filter() and Reduce() each put that idea to a different job.
Map returns a list
Map() runs the adding function over pairs from the two vectors. Map() also runs a function over a single vector, and every result still lands in a list with one item per value.
print(Map(function(a, b) a + b, c(1, 2), c(10, 20)))
print(Map(function(x) x * 3, c(2, 4, 5)))Filter keeps matches and Negate flips a test
Filter() keeps the values above 2. Negate() flips is.na into a test for present values, so the missing value drops out.
values <- c(1, 3, 2, 5, 4)
print(Filter(function(x) x > 2, values))
print(Filter(Negate(is.na), c(1, NA, 3)))Reduce folds values into one
Reduce() combines the values two at a time. The first call adds 1 to 4 into 10, and the second call multiplies 2, 3 and 4 into 24.
print(Reduce(function(a, b) a + b, 1:4))
print(Reduce(function(a, b) a * b, c(2, 3, 4)))Find a value and its place
Find() returns the first value above 3, which is 5. Position() returns the place of the first match and the place of the first value above 7.
values <- c(2, 5, 1, 8, 3)
print(Find(function(x) x > 3, values))
print(Position(function(x) x > 3, values))
print(Position(function(x) x > 7, values))mapply simplifies to a vector
Map() and mapply() run the same multiplying function over the same pairs. Map() returns a list, and mapply() simplifies the results into one vector.
print(Map(function(a, b) a * b, c(1, 2, 3), 10))
print(mapply(function(a, b) a * b, c(1, 2, 3), 10))Example
scores <- c(88, NA, 92, 75, NA, 100)
clean <- Filter(Negate(is.na), scores)
print(clean)
print(Map(function(x) x + 5, clean))
print(Reduce(function(a, b) a + b, clean))
print(Find(function(x) x > 90, clean))
print(Position(function(x) x > 90, clean))
print(mapply(function(x, add) x + add, clean, 5))Key points
- Map() runs a function over one or more vectors and returns a list.
- Filter() keeps the values that pass a test function.
- Negate() builds the opposite test, so Filter(Negate(is.na), values) drops missing values.
- Reduce() folds values into one result by combining them two at a time.
- Find() returns the first value that passes a test and Position() returns its place.
- mapply() runs a function over paired values and simplifies matching single results into a vector.
- Map() always returns a list, while mapply() tries to simplify its result.
In this example, Filter() with Negate() first drops the missing scores, and Reduce() totals the clean scores to 355. Map() adds five to each score as a list, while Find(), Position() and mapply() report the first score above 90, its place, and the raised scores as one vector.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท rdrr.io R Snippets
Exercise
What does mapply(function(a, b) a * b, c(1, 2, 3), 10) print?