How to convert dataframe column names from strings into arguments suitable for (qplot, ggplot2)?

妖精的绣舞 提交于 2019-12-29 05:20:30

问题


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')
...

but I want to do this generically, so that I can use the name of the column as a string "colname1".

In other words, how to write

plot_histogram_of_column <- function(df, colname) {
    # qplot(colname, data=df, geom='histogram') won't work
}

回答1:


Use ggplot and aes_string. Something like this:

ggplot(data = df, aes_string(x = colname)) + geom_histogram()

aes_string was written precisely for this purpose.



来源:https://stackoverflow.com/questions/8570855/how-to-convert-dataframe-column-names-from-strings-into-arguments-suitable-for

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!