Learning functional programming in R

Why use functional programming

Avoid intermediate objects

  • In any loop, the standard practice is to create a new list before the loop, do some processing for each element of the list in the loop and then add the processing result as an element to the new list (following the same index).

It makes programming more fun

  • Thinking about that index i is simply not as fun as working with the whole list.

It makes the code clearer to read

Without the cluttering of object assignment, you convey your objective faster.

Others

  • It earns you respect when your colleagues cannot understand your code and prevent them from messing around your code.
  • Of course, I am kidding on this aspect, because the primary goal of any code is to communicate in a collaborative environment.

Key components

  • map and its derivatives - control output type
  • the default parameter is a function name
  • use ~ when the function needs to be called with other parameters or more complicated patterns
  • use {} when there are multiple steps (e.g. assignment of values)
  • use .x (and .y) when you need to refer to the variable being mapped

Best practices

map should always be thought of as a recipe. The first argument is the ingredients stored in a list-like object and the second parameter is the procedure to be done on each of the ingredients.

Caveats

  • If it takes too long to come up with a functional programming solution, use for loop
  • There are other ways to batch process a list. For example, on a meta level using targetspattern

Some error:

reprex::reprex( { library(tidyverse) tibble(a=1) %>% mutate(b = ~ tibble(c=1)) }, session_info = TRUE )

Avatar
Tim

Personalizing medicine

Related