2014-01-20 67 views
1

使用for循環我有數據這樣的.csv文件:情節很多直方圖中的R

  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"

但我無法將它們轉換爲必要的格式。

任何幫助表示讚賞!

回答

2

您近距離了。我想你也試圖在最後得到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

hist(data$name)尋找名爲name的列,該列不在那裏。改爲使用hist(data[,name])

+0

This works too!非常感謝。 –

3

與繪製大量直方圖相比,更好的解決方案是在面板中繪製直方圖的一個繪圖。

爲此,您需要使用reshape2ggplot2包。

library(reshape2) 
library(ggplot2) 

首先,您需要將數據從寬轉換爲長表單。

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

然後創建value參數的一個ggplot在每個面板的直方圖,由每個元件分割(可以通過在調用上述melt傳遞value.name = "whatever"更改此名稱)。

(histograms <- ggplot(long_data, aes(value)) + 
    geom_histogram() + 
    facet_wrap(~ Element) 
)