将字符串作为变量传递给R中的日志函数

时间:2015-08-06 19:53:57

标签: r ggplot2

我正在尝试使用for循环生成一系列绘图,如下所示:

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
}

varList [[i]]适用于labs()和ggtitle但不幸的是,当我尝试同样的东西时,在aes()中得到log()函数它没有用,它给了我以下错误:< / p>

Error while parsing the string.

如果我用例如Var1替换arList [[i]]一切正常并且没有问题但是这样我只会一遍又一遍地使用相同的数字。我想知道是否有办法将此字符串转换为变量,我尝试了以下内容:

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

以上都没有让我得到正确答案。任何帮助将不胜感激。

由于

1 个答案:

答案 0 :(得分:1)

我使用Gregor和Roland的评论和建议解决了我的问题如下:

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
}
相关问题