13

我需要将 ggplot2 包装到另一个函数中,并且希望能够以与接受变量相同的方式解析变量,有人可以引导我朝着正确的方向前进。

例如,我们考虑下面的 MWE。

#Load Required libraries.
library(ggplot2)

##My Wrapper Function.
mywrapper <- function(data,xcol,ycol,colorVar){
  writeLines("This is my wrapper")
  plot <- ggplot(data=data,aes(x=xcol,y=ycol,color=colorVar)) + geom_point()
  print(plot)
  return(plot)
}

虚拟数据:

##Demo Data
myData <- data.frame(x=0,y=0,c="Color Series")

轻松执行的现有用法:

##Example of Original Function Usage, which executes as expected
plot <- ggplot(data=myData,aes(x=x,y=y,color=c)) + geom_point()
print(plot)

客观使用语法:

##Example of Intended Usage, which Throws Error ----- "object 'xcol' not found"
mywrapper(data=myData,xcol=x,ycol=y,colorVar=c)

上面给出了 ggplot2 包的“原始”用法示例,以及我想如何将它包装在另一个函数中。但是,包装器会引发错误。

我确信这适用于许多其他应用程序,并且可能已经回答了一千次,但是,我不确定这个主题在 R 中被“称为”什么。

4

2 回答 2

12

这里的问题是 ggplot在数据对象中查找column命名。xcol我建议切换到使用aes_string和传递要使用字符串映射的列名,例如:

mywrapper(data = myData, xcol = "x", ycol = "y", colorVar = "c")

并相应地修改您的包装器:

mywrapper <- function(data, xcol, ycol, colorVar) {
  writeLines("This is my wrapper")
  plot <- ggplot(data = data, aes_string(x = xcol, y = ycol, color = colorVar)) + geom_point()
  print(plot)
  return(plot)
}

一些备注:

  1. 个人喜好,我在 eg 周围使用了很多空格x = 1,对我来说这大大提高了可读性。没有空格,代码看起来就像一个大块。
  2. 如果您将绘图返回到函数外部,我不会在函数内部打印它,而是在函数外部打印它。
于 2013-04-30T08:28:20.603 回答
2

这只是对原始答案的补充,我知道这是一篇很老的帖子,但只是作为补充:

原始答案提供了以下代码来执行包装器:

mywrapper(data = "myData", xcol = "x", ycol = "y", colorVar = "c")

这里,data作为字符串提供。据我所知,这将无法正确执行。只有其中的变量aes_string作为字符串提供,而data对象作为对象传递给包装器。

于 2019-02-18T19:47:45.133 回答