使用R中的for循环绘制许多直方图

时间:2014-01-20 13:17:32

标签: r statistics histogram data-analysis

我有一个包含以下数据的.csv文件:

         RI    Na   Mg   Al    Si    K    Ca   Ba   Fe Type
1   1.51793 12.79 3.50 1.12 73.03 0.64  8.77 0.00 0.00  BWF
2   1.51643 12.16 3.52 1.35 72.89 0.57  8.53 0.00 0.00  VWF
3   1.51793 13.21 3.48 1.41 72.64 0.59  8.43 0.00 0.00  BWF
4   1.51299 14.40 1.74 1.54 74.55 0.00  7.59 0.00 0.00  TBL
5   1.53393 12.30 0.00 1.00 70.16 0.12 16.19 0.00 0.24 BWNF
6   1.51655 12.75 2.85 1.44 73.27 0.57  8.79 0.11 0.22 BWNF

我想为每个列的分布创建直方图。 我试过这个:

data<-read.csv("glass.csv")
names<-(attributes(data)$names)
for(name in names)
{
    dev.new()
    hist(data$name)
}

但我不断收到此错误:Error in hist.default(data$name) : 'x' must be numeric

我假设此错误是因为attributes(data)$names返回一组字符串,"RI" "Na" "Mg" "Al" "Si" "K" "Ca" "Ba" "Fe" "Type"

但我无法将它们转换为必要的格式。

感谢任何帮助!

3 个答案:

答案 0 :(得分:3)

你很亲密。我想你最后还试图获得Type

data<-read.csv("glass.csv")
# names<-(attributes(data)$names)
names<-names(data)
classes<-sapply(data,class)

for(name in names[classes == 'numeric'])
{
    dev.new()
    hist(data[,name]) # subset with [] not $
}

您也可以直接遍历列:

for (column in data[class=='numeric']) {
    dev.new()
    hist(column)
}

但是ggplot2是为多个情节而设计的。试试这样:

library(ggplot2)
library(reshape2)
ggplot(melt(data),aes(x=value)) + geom_histogram() + facet_wrap(~variable)

答案 1 :(得分:3)

不是绘制大量的直方图,更好的解决方案是在面板中绘制一个带直方图的图。

为此,您需要reshape2ggplot2个包。

library(reshape2)
library(ggplot2)

首先,您需要将数据从宽格式转换为长格式。

long_data <- melt(data, id.vars = "Type", variable.name = "Element")

然后创建一个value参数的ggplot(您可以通过在value.name = "whatever"调用中将melt传递给上面的(histograms <- ggplot(long_data, aes(value)) + geom_histogram() + facet_wrap(~ Element) ) 来更改其名称),每个面板中都有直方图,每个元件。

{{1}}

答案 2 :(得分:1)

hist(data$name)会查找名为name的列,但不存在。请改用hist(data[,name])