如何数据帧列的名称从字符串转换为适合(qplot,GGPLOT2)参数呢? [英] How to convert dataframe column names from strings into arguments suitable for (qplot, ggplot2)?

查看:183
本文介绍了如何数据帧列的名称从字符串转换为适合(qplot,GGPLOT2)参数呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个函数,它接受一个数据帧和图形在数据帧的直方图的所有列。

对于数据帧的列名我事先知道,我可以写

  qplot(colname1,数据= DF,GEOM ='直方图')
qplot(colname2,数据= DF,GEOM ='直方图')
...

但我想这样做一般,这样我可以使用列的名称作为一个字符串colname1

在换句话说,怎样写

  plot_histogram_of_column<  - 功能(DF,colname需要){
    #qplot(colname需要,数据= DF,GEOM ='直方图')将无法正常工作
}


解决方案

使用 ggplot aes_string 。事情是这样的:

  ggplot(数据= DF,aes_string(X = colname需要))+ geom_histogram()

aes_string 写precisely用于这一目的。

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
}

解决方案

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.

这篇关于如何数据帧列的名称从字符串转换为适合(qplot,GGPLOT2)参数呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆