如何将数据框列名从字符串转换为适合(qplot,ggplot2)的参数? [英] How to convert dataframe column names from strings into arguments suitable for (qplot, ggplot2)?
本文介绍了如何将数据框列名从字符串转换为适合(qplot,ggplot2)的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想编写一个函数,它接受一个数据帧,并将该数据帧中的所有列绘制为直方图.
I want to write a function that takes a dataframe, and graphs all the columns in that dataframe as histograms.
对于我事先知道其列名的数据框,我可以写
For a dataframe whose column names I know beforehand, I can write
qplot(colname1, data=df, geom='histogram')
qplot(colname2, data=df, geom='histogram')
...
但我想一般地这样做,以便我可以将列的名称用作字符串 "colname1"
.
but I want to do this generically, so that I can use the name of the column as a string "colname1"
.
也就是说,怎么写
plot_histogram_of_column <- function(df, colname) {
# qplot(colname, data=df, geom='histogram') won't work
}
推荐答案
使用 ggplot
和 aes_string
.像这样的:
Use ggplot
and aes_string
. Something like this:
ggplot(data = df, aes_string(x = colname)) + geom_histogram()
aes_string
正是为此目的而编写的.
aes_string
was written precisely for this purpose.
这篇关于如何将数据框列名从字符串转换为适合(qplot,ggplot2)的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文