函数内的ggplot:它什么时候不能识别参数,什么时候发生? [英] ggplot inside a function: when does it not recognize arguments and when does it?
问题描述
考虑以下两个函数:
library(ggplot2)
pre
testdata< - as数据帧(cbind(rep(c(1,4),each = 50),rbinom(100,50,5)))
names(testdata)< -c(group,值)
plotfun1 < - 函数(color){
ggplot(data = testdata,aes(x = factor(group,levels = c(0:4)),y =值))+
geom_boxplot(color = color)
}
plotfun2< - function(number){
ggplot(data = testdata,aes(x = (颜色='红')
}
$ b $ pplotfun1完美地工作,称为
plotfun1('red' )
会产生两个漂亮的红盒子图。然而,调用
plotfun2(4)
产生错误信息:
错误因素(group,levels = c(0:number)):object'number'not发现
显然在某些情况下,ggplot无法'找到'函数的参数,在某些情况下它是。这是怎么回事?
PS我知道有一个简单的解决方法:
plotfun3 < - 函数(数字){
pre>
plotdata < - testdata
plotdata $ group < - factor(plotdata $ group,levels = c(0:number))
ggplot(data = plotdata,aes(x = group,y = value))+
geom_boxplot(color ='red')
}
我只是想了解发生了什么。) 解决方案
<
plotfun2< - 函数(数字){
localenv < - environment()
ggplot(data = testdata,aes(x = factor(group,levels = c(0:number)),y = value),environment = localenv)+
geom_boxplot( color ='red')
}
plotfun2(4)
Consider the following two functions:
library(ggplot2)
testdata <- as.data.frame(cbind(rep(c(1, 4), each = 50), rbinom(100, 50, .5)))
names(testdata) <- c("group", "value")
plotfun1 <- function(color) {
ggplot(data = testdata, aes(x = factor(group, levels = c(0: 4)), y = value)) +
geom_boxplot(color = color)
}
plotfun2 <- function(number) {
ggplot(data = testdata, aes(x = factor(group, levels = c(0: number)), y = value)) +
geom_boxplot(color = 'red')
}
Plotfun1 works perfectly, calling
plotfun1('red')
yields two nice red boxplots. However calling
plotfun2(4)
yields the error message:
Error in factor(group, levels = c(0:number)) : object 'number' not found
apparently in some cases ggplot is not able to 'find' the arguments of the function, and in some cases it is. What is going on here?
PS I know there is an easy work around:
plotfun3 <- function(number) {
plotdata <- testdata
plotdata$group <- factor(plotdata$group, levels = c(0: number))
ggplot(data = plotdata, aes(x = group, y = value)) +
geom_boxplot(color = 'red')
}
I just want to understand what is going on.)
Capture the local environment and use it when plotting:
plotfun2 <- function(number) {
localenv <- environment()
ggplot(data = testdata, aes(x = factor(group, levels = c(0:number)), y = value), environment = localenv ) +
geom_boxplot(color = 'red')
}
plotfun2(4)
这篇关于函数内的ggplot:它什么时候不能识别参数,什么时候发生?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!