Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass variable or expression into `aes`

Tags:

r

ggplot2

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 found How 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)
like image 888
stata Avatar asked Nov 02 '14 12:11

stata


1 Answers

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

like image 181
David Arenburg Avatar answered Nov 15 '22 05:11

David Arenburg