r - Call to ggplot in a function with NSE -
the idea patch call ggplot in function.
the example:
library(dplyr) library(ggplot2) library(lazyeval) df <- data.frame(a=letters[1:10], b=2:11, c=3:12)) func <- function(name, dat=df) { output <- dat %>% select_(~a,name) %>% arrange_(interp(~desc(var), var=as.name(name))) plot <- ggplot(output, aes_string(x=reorder(~a,-name), y=b)) + geom_bar(stat='identity') print(plot) return(plot) } result <- func("b")
compiling gives:
error in -name : invalid argument unary operator.
i tried deparse
, substitute
. not sure got right combo. ideas?
reorder data before passing ggplot
. following code moves of column names around in ggplot
call, because otherwise you’d plotting a
against b
, regardless of name
argument — or intentional?
function (dat, name) { var = as.name(name) reord = list(interp(~ reorder(var, -var), var = var)) output = dat %>% select_(~a, name) %>% # not necessary. arrange_(interp(~ desc(var), var = var)) %>% mutate_(.dots = setnames(reord, name)) plot = ggplot(output, aes_string(x = 'a', y = name)) + geom_bar(stat = 'identity') plot(plot) plot } func(df, 'b')
i’m using mutate_(.dots = …)
form here. have @ dplyr’s “nse” vignette more information on usage.
Comments
Post a Comment