0

I need to graph data using different consolidation, and would like to do it inside ggplot.

x <- c(1,2,1,2,1,2,1,2,1)
cust <- c("a", "b", "c", "a", "b", "c", "a", "b", "c")
prod <- c("p1", "p1", "p2", "p2", "p1", "p1", "p2", "p2", "p1")
qty <- c(11,12,13,14,15,16,17,18,19)

dt <- data.table(x, cust, prod, qty)
rm(cust, prod, qty, x)

So, if I choose to consolidate by cust I get:

print.dt <- function(dt, x, qty, anchor_var_, geom) {
ggplot(dt, aes(x=x, y = qty, color = get(anchor_var_))) + 
    stat_summary(fun.y=sum, geom=geom, size=1.5 , aes(group=get(anchor_var_)))
}
anchor <- "cust"
print.dt(dt,x,qty,anchor, geom = "line")

enter image description here

Otherwise, If I choose to consolidate by prod, then:

anchor <- "prod"
print.dt(dt,x,qty,anchor, geom = "line")

enter image description here

However, this code calls get() twice. Is there another way to convert only once and apply for two instances? I tried:

print2.dt <- function(dt, x, qty, anchor_var_, geom) {
  anchor_var <- get(anchor_var_)
  ggplot(dt, aes(x=x, y = qty, color = anchor_var)) + 
    stat_summary(fun.y=sum, geom=geom, size=1.5 , aes(group=anchor_var))
}
anchor <- "prod"
print2.dt(dt,x,qty,anchor, geom = "line")

But it doesn´t work.

Fabio Correa
  • 1,257
  • 1
  • 11
  • 17
  • Are you attached to `get()`? You can program with ggplot2 using (soft deprecated) `aes_string()` or `aes_q()` or [tidyeval](https://www.tidyverse.org/articles/2018/07/ggplot2-tidy-evaluation/). – aosmith Feb 26 '19 at 21:47
  • I am not attached to `get()`. In fact, I tried first an `eval(quote())` solution with no success. I am new to these concepts. I will have a look at tidyeval suggestion. – Fabio Correa Feb 26 '19 at 22:05
  • 1
    @FabioCorrea: this might help https://stackoverflow.com/a/54755181/786542 – Tung Feb 26 '19 at 22:46

1 Answers1

2

From the rlang package you can use the !! operator on a sym(variable). This unquotes and evaluates in a similar manner that you would achieve with eval(parse(text = "variable")).

print2.dt <- function(dt, x, qty, anchor_var_, geom) {
  ggplot(dt, aes(x=x, y = qty, color = !! sym(anchor_var_))) + 
    stat_summary(fun.y=sum, geom=geom, size=1.5 , aes(group=!! sym(anchor_var_))
}

print2.dt(dt,x,qty,anchor_var_ = "prod", geom = "line")
Croote
  • 1,382
  • 1
  • 7
  • 15