1

I would like to pass variable name to var and do all sorts of things including ggplot.

Apparently UQ works for data manipulation, but doesn't work for ggplot2. So my function "foo" works but "foo1" doesn't.

What's the best solution?

set.seed(100)

dat <- tibble(`a` = rbinom(100, 1, 0.2), `b` = rnorm(100))


foo <- function(var)
{
  var_q <- enquo(var)

  dat %>% mutate(`d` = UQ(var_q) + 1)

}

foo(`a`)


foo1 <- function(var)
{
  var_q <- enquo(var)

  dat %>% mutate(`d` = UQ(var_q) + 1) %>% ggplot(aes(x=UQ(var_q), y=`b`)) + geom_point()
}

foo1(`a`)
Lab.J
  • 67
  • 1
  • 3
  • 2
    for ggplot you'll need `aes_string` – talat Nov 23 '17 at 07:50
  • I sort of get this idea, but how would you actually do it if my "x" is from a string and "y" is an actual column name? something like this seems doesn't work foo1 <- function(var) { var_q <- enquo(var) dat %>% mutate(`d` = UQ(var_q) + 1) %>% ggplot(aes_string(x=var_q, y="`b`")) + geom_point() } – Lab.J Nov 23 '17 at 07:53

1 Answers1

0
foo1 <- function(var) {
  var_q <- enquo(var)

  dat %>% 
    mutate(`d` = (!!var_q) + 1) %>% 
    ggplot(aes(x=eval(rlang::`!!`(var_q)), y=`b`)) + 
    geom_point()

 }
amarchin
  • 2,044
  • 1
  • 16
  • 32
  • 1
    Please provide an explanation for your answer. Your post is currently flagged as low quality. People are here to also learn, not only to have their problems solved. Thank you. – Dropout Nov 23 '17 at 09:30