1

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)
student
  • 1,001
  • 2
  • 12
  • 24

1 Answers1

0

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))))
}
Mike H.
  • 13,960
  • 2
  • 29
  • 39
  • That makes sense. Can you comment on why doing it (alternatively) via piping does not work. That is `... %>% print()`. – student Oct 11 '17 at 19:18
  • 3
    @student, because if you use a simple piping, you'll pass the `facet_wrap()` object to `print`. If you want to pipe, you could group the whole thing with `()` and then pass it to `print`. Something like `(iris %>% ...) %>% print()` – Mike H. Oct 11 '17 at 19:42