在ggplot中评估var

时间:2019-02-26 21:40:59

标签: r ggplot2 get

我需要使用不同的合并来绘制数据图,并希望在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)

因此,如果我选择通过cust进行合并,则会得到:

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

否则,如果我选择按prod合并,则:

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

enter image description here

但是,此代码两次调用get()。还有另一种方法只转换一次并申请两个实例吗?我尝试过:

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")

但这不起作用。

1 个答案:

答案 0 :(得分:2)

rlang包中,您可以在!!上使用sym(variable)运算符。取消报价并以与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")