Pass a variable or expression to `aes`
I wrote a function for plotting a histogram with factorial variables. When I run my function, an error message is displayed. Error in eval (expr, envir, enc): object 'dset' not found How to revise my function? Thank!
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)
source to share
Converted into an answer as seems useful
aes
is designed to evaluate unordered column names within a provided dataset ( dset
in your case). dset[, i]
is not a column name, but an entire column for which aes
it was not designed.
Fortunately, you can parse the column names with codes aes_string
. So using
aes_string(x = names(dset)[i])
instead
aes(x = dset[, i])
You need to solve your problem
source to share