2013-07-30 80 views
2

我在R中有一些數據,我想將其表示爲直方圖(實際上,我將有6個直方圖),然後將這些圖導出到Excel文件中。我剛剛使用hist()函數,但我也在嘗試使用ggplot2函數。每個直方圖都有10,000條數據,所以我不能只導出原始數據並在Excel中創建直方圖(我假設這會導致一個可笑的大小的Excel文件,這是我不想要的)。將直方圖從R導出到Excel

有什麼辦法可以導出我的圖?

+5

請參閱'?png'和'?ggsave'。如果你真的需要Excel(爲什麼要這麼做?),請將PNG(或您選擇的任何格式)導入到Excel中。 – Roland

+1

@Roland把它寫成答案。我認爲我們許多人會同意出口和進口是這類問題的答案。 – Dinre

+0

有沒有一種方法可以讓r代碼將.png導入到excel中? – Chris

回答

3

excel.link包是RDCOMClient的包裝。

以下示例僅適用於R 3.0.1中正常的RGUI(不是RStudio)。

# load package 
require(excel.link) 

# plot something 
plot(cos) 

# save graph to tmp file 
cos.plot=current.graphics() 

# add excel workbook 
xl.workbook.add() 

# add sheet to excel workbook 
xl.sheet.add() 

# put your graph starting at the top left in cell A1 
xl[a1]=list("Cosine plotting",cos.plot,"End of cosine plotting") 
1

另一個解決方案是離散化的數據存儲到數據幀和導出的數據幀經由未CSV文件或任何其他格式到Excel。

> x <- rnorm(1000) 
> h <- hist(x) 
> h 
$breaks 
[1] -3.5 -3.0 -2.5 -2.0 -1.5 -1.0 -0.5 0.0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 

$counts 
[1] 1 5 23 38 104 154 208 191 130 85 39 17 4 0 1 

$density 
[1] 0.002 0.010 0.046 0.076 0.208 0.308 0.416 0.382 0.260 0.170 0.078 0.034 0.008 0.000 0.002 

$mids 
[1] -3.25 -2.75 -2.25 -1.75 -1.25 -0.75 -0.25 0.25 0.75 1.25 1.75 2.25 2.75 3.25 3.75 

$xname 
[1] "x" 

$equidist 
[1] TRUE 

attr(,"class") 
[1] "histogram" 
> out <- data.frame(mid = h$mids, counts = h$counts) 
> write.table(out, file = "export.csv", row.names = FALSE, sep = ",") 

請注意,如果需要,也可以導出密度。