Search code examples
rggplot2scopeexpressionpurrr

Scope of identifiers in R formulas/expressions


I'm using as.ggplot from ggplotify to wrap some chord diagrams from the circlize package so I can arrange them nicely using patchwork. However, since as.ggplot takes a formula or expression as an argument, it seems to require that any identifiers are available in the global scope. I can get around this by assigning them globally with <<-, but this seems hacky. Is there another way around this?

In my case, I'm calling as.ggplot from inside of a function (using purrr::map), so that anything in there exists only in the local scope.

See these simple examples.

This first one fails because the implicit variable .x only exists within the scope of the anonymous map function:

library(ggplotify)
library(purrr)
  
plots <- map(1:10,~{
  as.ggplot(~plot(seq(.x)))
})
#> Error in `map()`:
#> ℹ In index: 1.
#> Caused by error in `seq()`:
#> ! object '.x' not found
plots[[10]]
#> Error in eval(expr, envir, enclos): object 'plots' not found

This next one succeeds because we're assigning it to something global:

library(ggplotify)
library(purrr)
  
plots <- map(1:10,~{
  x <<- .x
  as.ggplot(~plot(seq(x)))
})
plots[[10]]

Is there a way to do this without having to create the global variable using <<-?


Solution

  • Well, I ought to have spend just a minute or two longer googling before posting this question, because then answer is here: https://github.com/GuangchuangYu/ggplotify/issues/6#issuecomment-533442229

    And in terms of the above examples:

    library(ggplotify)
    library(purrr)
      
    plots <- map(1:10,~{
      as.ggplot(function() plot(seq(.x)))
    })
    plots[[10]]