yutannihilation · GitHub

(I originally reported this issue in tidyverse/purrr#103)

When I tried this example of purrr, I found the code sometimes fails with the following error:

#> Error: invalid term in model formula

The error above seems to occur when ggplot2 is loaded. A minimal code to reproduce the issue is bellow.

library(dplyr)
library(purrr)
d <- data_frame(training = list(mtcars, mtcars * 2))
# before ggplot2 is loaded, no error occurs
d %>%
  mutate(lm_result = map(training, ~ lm(mpg ~ wt, data = .)))
#> Source: local data frame [2 x 2]
#> 
#>               training lm_result
#>                 (list)    (list)
#> 1 <data.frame [32,11]>   <S3:lm>
#> 2 <data.frame [32,11]>   <S3:lm>
# after ggplot2, the very same code results in the error of `lm()`
library(ggplot2)
d %>%
  mutate(lm_result = map(training, ~ lm(mpg ~ wt, data = .)))
#> Error: invalid term in model formula

After some investigation, I found the .f is translated differently. But, I couldn't specify the cause...

debug_map <- function(.x, .f, ...) {print(.f); return(TRUE)}
library(dplyr)
library(purrr)
d <- data_frame(training = list(mtcars, mtcars * 2))
d %>%
  mutate(lm_result = debug_map(training, ~ lm(mpg ~ wt, data = .)))
#> ~lm(mpg ~ wt, data = .)
#> ...snip...
library(ggplot2)
d %>%
  mutate(lm_result = debug_map(training, ~ lm(mpg ~ wt, data = .)))
#> ~lm(list(manufacturer = c("audi", "audi", ...), model = c("a4", "a4", ...), displ = c(1.8, 1.8, ...), ...) ~ wt, data = .)
#> ...snip...
# If I use function(), it works fine
d %>%
  mutate(lm_result = debug_map(training, function(x) lm(mpg ~ wt, data = x)))
#> function(x) lm(mpg ~ wt, data = x)
#> ...snip...

Read the original on github.com ↗