将参数传递给ggplot
想要创建一个使用 ggplot 生成图形的函数。为了简单起见,典型的图形可能是“
ggplot(car, aes(x=speed, y=dist)) + geom_point()
我想创建的函数是”类型
f <- function(DS, x, y) ggplot(DS, aes(x=x, y=y)) + geom_point()
,但是“这”不起作用,因为 x 和 y 不是字符串。这个问题已经在之前的SO问题中注意到(例如,这个),但在我看来,没有提供令人满意的答案。如何修改上述函数以使其适用于任意数据帧?
would like to create a function that generates graphs using ggplot. For the sake of simplicity, the typical graph may be
ggplot(car, aes(x=speed, y=dist)) + geom_point()
The function I would like to create is of the type
f <- function(DS, x, y) ggplot(DS, aes(x=x, y=y)) + geom_point()
This however won't work, since x and y are not strings. This problem has been noted in previous SO questions (e.g., this one), but without providing, in my view, a satisfactory answer. How would one modify the function above to make it work with arbitrary data frames?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
一种解决方案是将 x 和 y 作为数据框 DS 中列的字符串名称传递。
然后将该函数调用为:
但是,您似乎不希望这样?您能举例说明为什么您需要不同的功能吗?是因为您不想将参数放在同一个数据框中吗?
One solution would be to pass x and y as string names of columns in data frame DS.
And then call the function as:
However, it seems that you don't want that? Can you provide an example why you would need different functionality? Is it because you don't want to have the arguments in the same data frame?
我认为可能有以下类型的代码,它们仅构建
aes
组件。然而,这似乎是一个复杂的方法。
I think it's possible the following type of codes, which only build the
aes
component.However, it seems to be complicated approach.
另一种选择是使用 do.call。这是来自工作代码的一行复制粘贴:
Another option is to use do.call. Here is a one line copy paste from a working code:
我能想到的一种方法是使用
match.call()
来访问传递给自定义绘图函数的参数/参数所包含的变量名称,然后使用eval()
> 关于他们。通过这种方式,如果您不喜欢的话,您可以避免将它们作为引用传递给您的自定义函数。One approach that I can think of is using
match.call()
to reach the variable names contained by the parameters/arguments passed to the custom plotting function and then useeval()
on them. In this way you avoid passing them as quoted to your custom function, if you do not like that.