[英]R - Passing arguments to `dplyr::select()` inside a wrapper
[英]Passing arguments to ggplot in a wrapper
我需要将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中该主题被称为“什么”。
这里的问题是xcol
在数据对象中查找名为xcol
的column
。 我建议切换到使用aes_string
并使用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)
}
一些说明:
x = 1
周围使用了很多空格,这对我来说大大提高了可读性。 没有空格,代码看起来像一个大块。 这只是原始答案的补充,我确实知道这是一篇很老的文章,但只是补充:
原始答案提供了以下代码来执行包装程序:
mywrapper(data = "myData", xcol = "x", ycol = "y", colorVar = "c")
在此, data
作为字符串提供。 据我所知,这将无法正确执行。 仅将aes_string
中的变量作为字符串提供,而将data
对象作为对象传递给包装器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.