问题描述
我编写了用因子变量绘制条形图的函数。当我运行我的功能时,显示错误消息。
eval中的错误(expr,envir,enclos):找不到对象'dset'
如何修改我的函数?谢谢!
x1 = factor(c(f,m,f,f,m, f,f,m,f,m))
x2 =因子(c(1,2,1,1,1 ,2,2,2,1,1))
y1 = c(10,11,12,13,14,15,16,17,18,19)
y2 = c(10,12,12,13,14,15,15,17,18,19)
y3 = c(10,12,12,14,14,15,15, 17,18,19)
bbb< - data.frame(x1,x2,y1,y2,y3)
myfunc< -function(dataframe){
库(ggplot2)
dset< -dataframe
for(i in 1:ncol(dset)){
if(is.factor(dset [,i])== T){
p3< -ggplot(data = dset,aes(x = dset [,i]))
p3< -p3 + geom_bar(color ='blue',fill ='blue')
print(p3)
}
}
}
myfunc(dataframe = bbb)
转换为答案,因为它看起来很有用
aes
用于评估提供的数据集范围内的未加引号的列名称(在您的案例中 dset
)。 dset [,i]
不是列名,而是整个列 aes
不是为了处理。
幸运的是,您可以将引用的列名解析为 aes_string
。因此,使用
aes_string(x = names(dset)[i])
而不是
aes(x = dset [ ,i])
应该解决您的问题
I wrote the function to plot bar graph with factor variables. When I run my function,The error message was showed.Error in eval(expr, envir, enclos) : object 'dset' not foundHow to revise my function? Thank you!
x1=factor(c("f","m","f","f","m","f","f","m","f","m"))
x2=factor(c("1","2","1","1","1","2","2","2","1","1"))
y1=c(10,11,12,13,14,15,16,17,18,19)
y2=c(10,12,12,13,14,15,15,17,18,19)
y3=c(10,12,12,14,14,15,15,17,18,19)
bbb<- data.frame(x1,x2,y1,y2,y3)
myfunc<-function(dataframe){
library(ggplot2)
dset<-dataframe
for (i in 1:ncol(dset)){
if (is.factor(dset[,i])==T){
p3<-ggplot(data=dset, aes(x=dset[,i]))
p3<-p3+geom_bar(colour='blue',fill='blue')
print(p3)
}
}
}
myfunc(dataframe=bbb)
Converted to an answer, as it seems useful
aes
is designed to evaluate unquoted column names within the scope of the provided dataset (dset
in your case). dset[, i]
is not a column name, rather a whole column which aes
wasn't designed to deal with.
Fortunately, you can parse quoted column names to aes_string
. Thus, using
aes_string(x = names(dset)[i])
instead of
aes(x = dset[, i])
Should solve your problem
这篇关于将变量或表达式传递给`aes`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!