How to implement mappers in R?

Asked

Viewed 60 times

5

I would like the answer to contain information on:

  • What are mappers?

  • How to create a mapper on R?

  • In what situations mappers are used (their role in functional programming)?

1 answer

6


A mapper is a function that relates elements of a set to elements of the same or another set. This is a mathematical concept.

To better understand what a mapper in the context of programming we first need to understand what a functional.

A functional is a function that takes at least one function as argument and returns a vector/list. There is a very important category that functional are the maps.

Essentially, a map is a hidden loop. They receive a vector and a function and apply this function to each element of the received vector. A simple implementation in R could be as follows:

meu_map <- function(x, f) {
  out <- vector(mode = "list", length = length(x))
  for (i in seq_along(x)) {
    out[[i]] <- f(x[[i]])
  }
  out
}

meu_map(1:10, function(x) x^2)

mapper in programming is the name we give to the function we pass as an argument to the functionalities of the class map.

Contrary to what many think, use maps in R is not related to the performance but the readability of the code. It is more or less the same idea to use for instead of using while. It is also worth noting that in R, we only use maps when there is no vector option to do the same thing - in the above example the surest would be to write simply x^2.

At R base, we create mappers in the same way that we create functions, although we can use them as anonymous functions. In the case of lapply which is the most famous functional of R, the mappers are the second argument in the calls below.

lapply(mtcars, mean)
lapply(mtcars, function(x) sum(x)/length(x))

The package purrr implements a slightly different way of writing anonymous functions if you will use them as mappers.

library(purrr)
map(mtcars, ~sum(.x)/length(.x))

This new notation makes writing anonymous functions much less verbose, making code simpler. In this case, write ~sum(.x)/length(.x) is equivalent to writing: function(.x) sum(.x)/length(.x). Note that it always assumes that the function argument has the name .x.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.