Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass string as variable to log function in R

Tags:

r

ggplot2

I am trying to generate a series of plots using a for loop like the following:

varList = list("Var1","Var2","Var3")
plot_list = list()
for (i in 1:3) {
    gg = ggplot(data_set,aes(x=log(varList[[i]])),fill=factor(RETAINED))) 
    gg = gg + geom_density(alpha=.3) + labs(x = varList[[i]],y="Density") 
    gg = gg + ggtitle(paste("Distribution of ",varList[[i]],sep=" ")) 
    plot_list[[i]] = gg
}

The varList[[i]] works fine for labs() and ggtitle but unfortunately when I am trying the same thing got log() function in aes() it does not work out and it gives me the following error:

Error while parsing the string.

If I replace arList[[i]] with for example Var1 everything works fine and there is no problem but that way I will only have the same figure over and over again. I am wondering if there is a way to convert this string to a variable and I have tried the followings:

  • get() function
  • parse(text = varList[[i]])
  • eval(parse(text = varList[[i]]))

And none of the above led me to the correct answer. Any help would be much appreciated.

Thanks

like image 409
ahajib Avatar asked Sep 17 '26 16:09

ahajib


1 Answers

I solved my problem using Gregor and Roland comments and suggestions as following:

varList = list("Var1","Var2","Var3")
plot_list = list()
for (i in 1:3) {
    gg = ggplot(data_set,aes(xfill=factor(RETAINED)))
    gg = gg + aes_string(x = sprintf("log(%s)", varList[[i]])) 
    gg = gg + geom_density(alpha=.3) + labs(x = varList[[i]],y="Density") 
    gg = gg + ggtitle(paste("Distribution of ",varList[[i]],sep=" ")) 
    plot_list[[i]] = gg
}
like image 58
ahajib Avatar answered Sep 19 '26 07:09

ahajib