如何在另一个函数中传递/评估函数参数以用于 ggplot?

Posted

技术标签:

【中文标题】如何在另一个函数中传递/评估函数参数以用于 ggplot?【英文标题】:How to pass / evaluate function arguments within another function for use with ggplot? 【发布时间】:2011-10-17 11:49:23 【问题描述】:

请考虑以下代码:

test <- function(x,n)

selection<-names(x)[n]
graph <- ggplot(x, aes(factor(selection)))
graph + geom_bar()


test(mtcars,1)

它会抛出一个错误,导致 R 找不到选择。我也玩过substituteevalget,但没有成功。我找到了this similar question 并认为我理解了Joris' 的答案,但也不能对 ggplot 的参数使用相同的技巧。

【问题讨论】:

【参考方案1】:

您可以为此目的使用aes_string。所以test应该是这样的:

test <- function(x,n)
  graph <- ggplot(x, aes_string(x = names(x)[n]))
  graph + geom_bar()

【讨论】:

感谢 koshke,我希望我不会一直错过这么多小技巧。然而,它有助于理解 ggplot 是如何编写的。

以上是关于如何在另一个函数中传递/评估函数参数以用于 ggplot?的主要内容,如果未能解决你的问题,请参考以下文章