如何在另一个函数中传递/计算函数参数以用于ggplot? [英] How to pass / evaluate function arguments within another function for use with ggplot?

查看:136
本文介绍了如何在另一个函数中传递/计算函数参数以用于ggplot?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码:

Please consider the following code:

test <- function(x,n){

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

test(mtcars,1)

它引发错误,导致R无法找到选择。我也玩过替代 eval get 没有成功。我发现这个类似的问题,并认为我明白 Joris'答案,但不能对ggplot的参数使用相同的技巧。

It throws an error cause R can't find selection. I also played around with substitute, eval and get without success. I found this similar question and thought I understood Joris' answer but can't use the same trick for arguments of ggplot as well.

推荐答案

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

you can use aes_string for this purpose. So test should be like this:

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

这篇关于如何在另一个函数中传递/计算函数参数以用于ggplot?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆