5
votes

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)
1
@ David Arenburg If changed, the graph was wrong.stata
Sorry, Change aes(x=dset[,i]) to aes_string(x=names(dset)[i])David Arenburg
@ David Arenburg Perfect! Thank you very much.stata

1 Answers

7
votes

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