1

For some reason, with identical arguments, purrr::walk and purrr::map exhibit different behavior.

Here is a minimal reproducible example:

library(ggplot2)
library(purrr)
library(dplyr)

suv <- mpg %>% filter(class == "suv")
compact <- mpg %>% filter(class == "compact")

purrr::walk(list(suv, compact), ~ggplot(.,aes(displ, hwy)) + geom_point())
# No output

purrr::map(list(suv, compact), ~ggplot(.,aes(displ, hwy)) + geom_point())
# Generates two plots

From looking at the purrr source code, I can tell that walk is just a wrapper around map that invisibly returns the .x argument:

purrr::walk <- function(.x, .f, ...)
{
    map(.x, .f, ...)
    invisible(.x)
}

For that reason, I can't understand why the behavior would be different. Does this have something to do with lazy-evaluation? Is the fact that the return value of map isn't being used preventing .f from being evaluated?

jgaeb
  • 197
  • 8
  • 2
    Well, the `ggplot()` object doesn't actually draw a plot. It creates a ggplot object. That object is only rendered to a plot when you `print()` that object. Normally when you run a command in R, the result is automatically printed for you by the console. But when you do a `walk`, nothing is printed() so you get no plots (but the `ggplot` function did all the work of calculating the information for the plot). You can add a `print()` around the `ggplot()` in the walk to get it to render. – MrFlick Mar 29 '19 at 19:38
  • Thank you! That makes sense. – jgaeb Mar 29 '19 at 19:40

0 Answers0