walk()

  • We use walk() when we want to call a function for it side effect(s) rather than its return value, like generating plots, write.csv(), or ggsave(). If you don’t want a return value, map() will print more info than you may want.
map(1:3, ~cat(.x, "\n"))
#> 1 
#> 2 
#> 3
#> [[1]]
#> NULL
#> 
#> [[2]]
#> NULL
#> 
#> [[3]]
#> NULL
  • for these cases, use walk() instead
walk(1:3, ~cat(.x, "\n"))
#> 1 
#> 2 
#> 3

cat() does have a result, it’s just usually returned invisibly.

cat("hello")
#> hello

(cat("hello"))
#> hello
#> NULL

We can use pwalk() to save a list of plot to disk. Note that the “p” in pwalk() means that we have more than 1 (or 2) variables to pipe into the function. Also note that the name of the first argument in all of the “p” functions is now .l (instead of .x).

plots <- mtcars |>  
  split(mtcars$cyl) |>  
  map(~ggplot(.x, aes(mpg,wt)) +
        geom_point())

paths <- stringr::str_c(names(plots), '.png')

pwalk(.l = list(paths,plots), .f = ggsave, path = tempdir())
#> Saving 7 x 5 in image
#> Saving 7 x 5 in image
#> Saving 7 x 5 in image
pmap(.l = list(paths,plots), .f = ggsave, path = tempdir())
#> Saving 7 x 5 in image
#> Saving 7 x 5 in image
#> Saving 7 x 5 in image
#> [[1]]
#> [1] "/tmp/RtmpRCE8He/4.png"
#> 
#> [[2]]
#> [1] "/tmp/RtmpRCE8He/6.png"
#> 
#> [[3]]
#> [1] "/tmp/RtmpRCE8He/8.png"
  • walk, walk2 and pwalk all invisibly return .x the first argument. This makes them suitable for use in the middle of pipelines.

  • note: I don’t think that it is “.x” (or “.l”) that they are returning invisibly. But I’m not sure what it is. Hadley says:

purrr provides the walk family of functions that ignore the return values of the .f and instead return .x invisibly.

But not in the first cat() example, it is the NULL values that get returned invisibly (those aren’t the same as .x).