函数内函数内的ggplot:传递参数
ggplot within a function within a function: passing arguments
我很难弄清楚如何通过对 ggplot 的嵌套函数调用传递参数。一个例子将有助于说明:
library('tidyverse')
dset <- tibble(
xvar = 1:5,
yvar = 6:10
)
plot_inner <- function(.outcome) {
ggplot(dset, aes(x=xvar)) +
geom_line(aes_(y=substitute(.outcome)))
}
现在我可以调用 plot_inner(.outcome=yvar)
,它会正确绘制 yvar
与 xvar
的折线图。但是,当我想将 plot_inner()
嵌套在另一个函数中时,问题就出现了:
plot_outer <- function(..outcome) {
plot_inner(.outcome=..outcome)
}
目的是让我调用 plot_outer()
并将 ..outcome
指定为 dset
的列,然后传递给 plot_inner()
中的 .outcome
然后由 ggplot()
绘制。但它不起作用:
> plot_outer(..outcome=yvar)
Error in FUN(X[[i]], ...) : object '..outcome' not found
我尝试了 parse()
、eval()
、substitute()
和 deparse()
的各种组合,但无法弄清楚如何制作这种嵌套函数打电话工作。
我也尝试了另一种方法:
plot_inner_2 <- function(.outcome) {
.outcome <- enquo(.outcome)
dset %>% rename(value = UQ(.outcome)) %>%
ggplot(aes(xvar, value)) +
geom_line()
}
通过这种方法,我可以调用 plot_inner_2(.outcome=yvar)
,它可以正确生成 yvar
与 xvar
的折线图。但是,当我尝试将其嵌套在另一个函数中然后调用外部函数时,我 运行 再次陷入错误:
plot_outer_2 <- function(..outcome) {
plot_inner_2(.outcome=..outcome)
}
> plot_outer_2(..outcome=yvar)
Error: `..outcome` contains unknown variables
如有任何帮助,我们将不胜感激。我更喜欢按照我尝试过的第一种方法的解决方案,但是如果有人有按照第二种方法或完全其他方法的解决方案,我很乐意学习任何有效的方法。
按照@aosmith 评论中的 link,在 plot_outer()
函数中将 plot_inner()
包裹在 eval(substitute())
内似乎是一个解决方案。
plot_outer <- function(..outcome) {
eval(substitute(plot_inner(.outcome=..outcome)))
}
现在对 plot_outer(..outcome=yvar)
的调用按预期工作,将 yvar
传递给 inner_plot()
中的 .outcome
,然后传递给 ggplot()
并绘制xvar
.
我很难弄清楚如何通过对 ggplot 的嵌套函数调用传递参数。一个例子将有助于说明:
library('tidyverse')
dset <- tibble(
xvar = 1:5,
yvar = 6:10
)
plot_inner <- function(.outcome) {
ggplot(dset, aes(x=xvar)) +
geom_line(aes_(y=substitute(.outcome)))
}
现在我可以调用 plot_inner(.outcome=yvar)
,它会正确绘制 yvar
与 xvar
的折线图。但是,当我想将 plot_inner()
嵌套在另一个函数中时,问题就出现了:
plot_outer <- function(..outcome) {
plot_inner(.outcome=..outcome)
}
目的是让我调用 plot_outer()
并将 ..outcome
指定为 dset
的列,然后传递给 plot_inner()
中的 .outcome
然后由 ggplot()
绘制。但它不起作用:
> plot_outer(..outcome=yvar)
Error in FUN(X[[i]], ...) : object '..outcome' not found
我尝试了 parse()
、eval()
、substitute()
和 deparse()
的各种组合,但无法弄清楚如何制作这种嵌套函数打电话工作。
我也尝试了另一种方法:
plot_inner_2 <- function(.outcome) {
.outcome <- enquo(.outcome)
dset %>% rename(value = UQ(.outcome)) %>%
ggplot(aes(xvar, value)) +
geom_line()
}
通过这种方法,我可以调用 plot_inner_2(.outcome=yvar)
,它可以正确生成 yvar
与 xvar
的折线图。但是,当我尝试将其嵌套在另一个函数中然后调用外部函数时,我 运行 再次陷入错误:
plot_outer_2 <- function(..outcome) {
plot_inner_2(.outcome=..outcome)
}
> plot_outer_2(..outcome=yvar)
Error: `..outcome` contains unknown variables
如有任何帮助,我们将不胜感激。我更喜欢按照我尝试过的第一种方法的解决方案,但是如果有人有按照第二种方法或完全其他方法的解决方案,我很乐意学习任何有效的方法。
按照@aosmith 评论中的 link,在 plot_outer()
函数中将 plot_inner()
包裹在 eval(substitute())
内似乎是一个解决方案。
plot_outer <- function(..outcome) {
eval(substitute(plot_inner(.outcome=..outcome)))
}
现在对 plot_outer(..outcome=yvar)
的调用按预期工作,将 yvar
传递给 inner_plot()
中的 .outcome
,然后传递给 ggplot()
并绘制xvar
.