0

I try to create a simple function which allow to draw a ggvis plot. I know that I have to use non-standard evaluation here that's why I use intercept function of lazyeval package:

test_fn <- function(data,xvar, yvar){

        plot <- 
                data %>% 
                ggvis(lazyeval::interp(~x, x = as.name(xvar)), 
                      lazyeval::interp(~y, y = as.name(yvar))) %>% 
                layer_points()
        return(plot)
}

EDIT:

This function works fine:

test_fn(mtcars,'mpg', 'qsec')

But what should I do additionally in order to a given command works:

test_fn(mtcars,mpg, qsec)
Nicolabo
  • 1,337
  • 12
  • 30
  • 1
    Can you clarify what exactly doesn't work? Using your function, `test_fn(mtcars, "mpg", "wt")` makes a plot. Consider including a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) in your question. – aosmith Jan 04 '16 at 18:27
  • 1
    Also note that you can use the `prop` function from *ggvis* for this sort of task instead of `lazyeval::interp`. It would look like, e.g., `ggvis(prop("x", as.name(xvar)), prop("y", as.name(yvar)))`, but see the help page for more examples. – aosmith Jan 04 '16 at 18:33

1 Answers1

1

One option is to use deparse(substitute(...)) for this sort of non-standard evaluation. It makes the function longer but can be convenient for the user.

Here's what it could look like using the lazyeval::interp method:

test_fn <- function(data, xvar, yvar){
    x <- deparse(substitute(xvar))
    y <- deparse(substitute(yvar))
    plot <- 
        data %>% 
        ggvis(lazyeval::interp(~x, x = as.name(x)), 
              lazyeval::interp(~y, y = as.name(y))) %>% 
        layer_points()
    return(plot)
}

And here's the version with prop:

test_fn <- function(data, xvar, yvar){
    x <- deparse(substitute(xvar))
    y <- deparse(substitute(yvar))
    plot <- 
        data %>% 
        ggvis(prop("x", as.name(x)), 
              prop("y", as.name(y))) %>% 
        layer_points()
    return(plot)
}

Both work using unquoted variable names:

test_fn(mtcars, mpg, wt)

enter image description here

aosmith
  • 34,856
  • 9
  • 84
  • 118