Search code examples
rggplot2purrrnse

purrr and ggplot function are not displaying plot (NSE issue)


I suspect this is a problem dealing with NSE. But why isn't these two approaches work and how can I get them to work.

temp1 <- function(x){
  iris %>% 
    ggplot(aes(Sepal.Length, Sepal.Width)) +
    geom_point() +
    facet_wrap(as.formula(paste("~", x)))
}
walk('Species', temp1)


temp2 <- function(x){
  x <- as.name(x)
  iris %>% 
    ggplot(aes(Sepal.Length, Sepal.Width)) +
    geom_point() +
    facet_wrap(~ x)
}
walk('Species', temp2)

Solution

  • To me, it doesn't appear to be an NSE issue. If you read ?walk it says (emphasis added by me):

    walk() calls .f for its side-effect and returns the original input

    Try:

    t <- walk('Species', temp1)
    t
    #[1] "Species"
    

    I think you can get what you want if you add an explicit print to your ggplot. E.g. change temp1 to be:

    temp1 <- function(x){
      print(iris %>% 
            ggplot(aes(Sepal.Length, Sepal.Width)) +
            geom_point() +
            facet_wrap(as.formula(paste("~", x))))
    }